在我尝试使用 C# 在 Selenium 中实现自动化的手动测试用例中,它说:“登录并激活复选框‘记住我’,关闭浏览器,打开浏览器,检查用户是否仍然登录。 "
手动执行,这当然是成功的。在 Chrome 中使用 Selenium,我总是会在 session 之间丢失 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 在 session 之间保留 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();
}
}
关于c# - 如何在不丢失 cookie 的情况下刷新我的 Selenium ChromeDriver 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155759/