解决方案
我们没有找到保存 Cookie 的专有方法,所以我们采用自己的方案:
1)将 Cookie 对象保存到文件,
2)在启动时,再载入 Cookie 对象
适用于 Java 语言的方法
将 Cookie 保存到文件:
private void cookieWriteToFile(WebDriver webDriver) throws Exception {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/path/to/cookie.bin"));
objectOutputStream.writeObject(webDriver.manage().getCookies());
}
从文件中读取 Cookie:
private void cookieWriteToFile(WebDriver webDriver) throws Exception {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("/path/to/cookie.bin"));
Set<Cookie> cookies = (Set<Cookie>) objectInputStream.readObject();
for (Cookie cookie : cookies) {
webDriver.manage().addCookie(cookie);
}
}
该方法的本质是:保存二进制对象到文件,之后从文件恢复二进制对象
注意事项,该方法适用于 Java 语言,而 Groovy 语言存在其他问题。
适用于 Groovy 语言的方法
参考 Object 笔记。
参考文献
Selenium Grid Tutorial: Hub & Node (with Example)
Selenium Java / API / Overview