如何在不丢失 cookie 的情况下刷新我的 Selenium ChromeDriver 实例



在手动测试用例中,我正在尝试使用 C# 在 Selenium 中自动化,它说:"登录时激活了复选框'记住我',关闭浏览器,打开浏览器,检查用户是否仍在登录。

手动执行,这当然是成功的。在Chrome中使用Selenium,我总是在会话中丢失cookie。

到目前为止我尝试过:

public static void RefreshDriver(TestParams testParams)
{
    var cookies = testParams.Target.Driver.Manage().Cookies.AllCookies;
    var url = new Uri(testParams.Target.Driver.Url);
    testParams.Target.Driver.Quit();
    testParams.Target = testParams.Target.Clone(); // creates new ChromeDriver()
    string temp = url.GetLeftPart(UriPartial.Authority);
    testParams.Target.Driver.Navigate().GoToUrl(temp);
    foreach (Cookie cookie in cookies)
    {
        testParams.Target.Driver.Manage().Cookies.AddCookie(cookie);
    }
    testParams.Target.Driver.Navigate().GoToUrl(url);
}

这就是我创建ChromeDriver的方式:

private ChromeDriver _CreateChromeDriver(string httpProxy)
{
    var options = new ChromeOptions();
    string tempDir = @"C:UsersKimmyDocumentsMyUserDataDir";
    options.AddArgument("user-data-dir=" + tempDir);
    if (!string.IsNullOrEmpty(httpProxy))
    {
        options.Proxy = new Proxy {HttpProxy = httpProxy};
    }
    return new ChromeDriver(options);
}

当我执行我的测试用例并到达带有 RefreshDriver() 的部分时,首先我的用户再次登录。但是,一旦我开始将产品添加到购物篮,我的用户突然不再登录。

有没有办法告诉 Chrome 在会话中保留 Cookie,而无需手动保存和恢复 Cookie?

我用java编程语言写了一个类似的程序。请参考下面的代码。它可能对您有所帮助。出于可读性的目的,程序有许多注释。

public class CookieHandling {
public WebDriver driver;
    @Test
    public void test() throws InterruptedException{
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://gmail.com/");
        //Login. So new session created
        driver.findElement(By.id("Email")).sendKeys("email id here");
        driver.findElement(By.id("Email")).sendKeys(Keys.ENTER);
        driver.findElement(By.id("Passwd")).sendKeys("mail password here");
        driver.findElement(By.id("Passwd")).sendKeys(Keys.ENTER);
        //Store all set of cookies into 'allCookies' reference var.
        Set<Cookie> allCookies=driver.manage().getCookies();
        driver.quit();//Quitting the firefox driver
        Thread.sleep(3000);
        //Opening the chrome driver
        System.setProperty("webdriver.chrome.driver","C:\Users\kbmst\Desktop\temp\chromedriver.exe");
        //System.setProperty("webdriver.ie.driver","C:\Users\kbmst\Desktop\temp\IEDriverServer.exe");
        driver=new ChromeDriver();
        driver.manage().window().maximize();
        //It is very import to open again the same web application to set the cookies.
        driver.get("http://www.gmail.com/");
        //Set all cookies you stored previously
        for(Cookie c:allCookies){
            driver.manage().addCookie(c);
        }
        //Just refresh using navigate()
        driver.navigate().refresh();
    }
}

最新更新