【问题标题】:Best Way to Preserve Cookies for the Long Term from One Selenium Session to Another?从一个 Selenium 会话到另一个会话长期保存 Cookie 的最佳方法?
【发布时间】:2021-06-12 07:34:18
【问题描述】:

我正在使用Selenium WebDriver 来启动特定的 Firefox 配置文件。通常,Selenium 会创建一个模仿现有 Firefox 配置文件的 FF 临时安装,然后在调用 webdriver.close() 后将其删除。

但是,我需要能够通过 Selenium 启动 Firefox WebDriver 并为以后的会话保留某些登录 cookie,这样我每次登录时都不会被要求输入密码和/或验证码帐户。我已经看到了一些解决这个问题的方法,但每种方法都有自己的问题:

1) 识别 Selenium 创建的临时文件,并将 cookies.sqlite 复制到原始 FF Profile 安装文件夹中。我看到这种方法的问题是我同时启动了许多 Selenium 实例,那么我将如何确定哪个临时文件夹对应于特定的 WebDriver 会话?另外,是否可以将cookie附加到原始安装文件而不是覆盖原始文件?

2) 一个user suggested 来电:

Set<Cookie> allCookies = driver.manage().getCookies();

在调用 driver.close() 之前,然后通过调用将 cookie 添加到下一个 WebDriver 会话:

for(Cookie cookie : allCookies)
{
    driver.manage().addCookie(cookie);
}

我看到这种方法的问题是我需要长期(即永远)保留 cookie,并且我无法将所有会话的 cookie 存储在内存中。即使可以,当程序存在或主机关闭时,cookie 数据也会丢失。此外,getCookies() 仅返回当前域的 cookie,而 addCookie() 只允许添加域与当前 URL 的域相同的 cookie。因此,在获取或设置 cookie 时,首先访问正确的 URL 很重要,正如 by one commenter 所指出的那样。我想在新的 FF 会话启动时立即从多个域加载 cookie。

3) 另一个选项可能是首先阻止 Firefox 在新位置创建临时文件(即重定向到原始 FF 安装目录)并防止 FF 在退出时删除临时文件.这样的事情可行吗?

我见过其他一些方法,但它们要么仅解决与 Chrome(不是 Firefox)或 Python 相关的问题,要么存在上述缺陷之一。

在Java + Firefox中可以用什么方法来解决这个问题?

谢谢!

【问题讨论】:

    标签: java selenium selenium-webdriver firefox cookies


    【解决方案1】:

    最适合您的解决方案是当您想要存储它们以将您的 cookie 存储在 JSON 文件中,这样您以后就可以在浏览器中加载它们。

    这里有一个如何存储它们的快速教程:TUTORIAL

    用 JSON 编写:

    import java.io.FileWriter;
    import java.io.IOException;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    
    public class WriteJSONExample
    {
      @SuppressWarnings("unchecked")
      public static void main( String[] args )
    {
        //First Employee
        JSONObject employeeDetails = new JSONObject();
        employeeDetails.put("firstName", "Lokesh");
        employeeDetails.put("lastName", "Gupta");
        employeeDetails.put("website", "howtodoinjava.com");
         
        JSONObject employeeObject = new JSONObject(); 
        employeeObject.put("employee", employeeDetails);
         
        //Second Employee
        JSONObject employeeDetails2 = new JSONObject();
        employeeDetails2.put("firstName", "Brian");
        employeeDetails2.put("lastName", "Schultz");
        employeeDetails2.put("website", "example.com");
         
        JSONObject employeeObject2 = new JSONObject(); 
        employeeObject2.put("employee", employeeDetails2);
         
        //Add employees to list
        JSONArray employeeList = new JSONArray();
        employeeList.add(employeeObject);
        employeeList.add(employeeObject2);
         
        //Write JSON file
        try (FileWriter file = new FileWriter("employees.json")) {
            //We can write any JSONArray or JSONObject instance to the file
            file.write(employeeList.toJSONString()); 
            file.flush();
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }
    

    读取 JSON:

    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
     
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
     
    public class ReadJSONExample 
    {
        @SuppressWarnings("unchecked")
        public static void main(String[] args) 
        {
            //JSON parser object to parse read file
            JSONParser jsonParser = new JSONParser();
             
            try (FileReader reader = new FileReader("employees.json"))
            {
                //Read JSON file
                Object obj = jsonParser.parse(reader);
     
                JSONArray employeeList = (JSONArray) obj;
                System.out.println(employeeList);
                 
                //Iterate over employee array
                employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
     
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
     
        private static void parseEmployeeObject(JSONObject employee) 
        {
            //Get employee object within list
            JSONObject employeeObject = (JSONObject) employee.get("employee");
             
            //Get employee first name
            String firstName = (String) employeeObject.get("firstName");    
            System.out.println(firstName);
             
            //Get employee last name
            String lastName = (String) employeeObject.get("lastName");  
            System.out.println(lastName);
             
            //Get employee website name
            String website = (String) employeeObject.get("website");    
            System.out.println(website);
        }
    }
    

    【讨论】:

    • 这个答案很模糊..我不认为它解决了这个问题
    • 这就是我用于我的 selenium 自动化的东西。您只需将 cookie 保存在 JSON 文件中,这样您就可以将它们加载到另一个 selenium 会话中。这样,您的 cookie 将在您的会话中保存,您可以随时使用它们。
    • 感谢您的澄清。您介意提供一个完整的示例来说明如何在 Java 中执行此操作以及您的答案吗?然后我会接受你的回答..
    • 如何首先获取所有 cookie(来自所有域),以便将它们转换为 JSON?正如我在 OP 中所说,WebDriver 仅从当前 URL 返回 cookie。另外,当我再次启动 WebDriver 时,如何将它们加载到 WebDriver 中?谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 2013-01-28
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多