如何在不丢失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:\Users\Kimmy\Documents\MyUserDataDir"; 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 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(); } }