首页 > 解决方案 > 如何使用 Java + Selenium WebDriver 导出/导入 cookie

问题描述

我有一个使用 Java + Selenium WebDriver 的工具,我每天都运行它。如何导出 cookie、历史记录......并像普通浏览器一样导入/重用它以供下次执行。

标签: javaseleniumselenium-webdriverselenium-firefoxdriver

解决方案


我们可以将浏览器的配置文件信息写入 JSON 文件,然后用相同的配置文件实例化新的浏览器。

FirefoxProfile类提供toJson()方法写入配置文件信息

FirefoxProfile类提供fromJson()方法来检索配置文件信息

FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(
new File("src/test/resources/extensions/anyextenstion.file"));
String json = profile.toJson();
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(FirefoxProfile.fromJson(json));
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);

推荐阅读