我想运行一次登录脚本,每当我再次运行它时,它都不会要求我登录。
请帮助我如何处理硒中的这种情况。
答案 0 :(得分:0)
访问Selenium文档指南Generating application state在那里提到
应该创建一种方法来访问AUT *(例如,使用API登录并设置Cookie)
您可以编写一种在登录后保存所有cookie的方法。现在,在需要登录的测试中使用这些相同的cookie。
driver = new ChromeDriver();
driver.get("https://www.somesite.com/login/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElementById("email").sendKeys("someemail@gmail.com");
driver.findElementById("pass").sendKeys("pass@312");
driver.findElementById("send2").click();
// after successful login get cookies and store in a map for further use
Set<Cookie> cookies = driver.manage().getCookies();
Map<String, Object> cookieMap = new HashMap<>();
cookieMap.put("myCookies", cookies);
driver.quit();
// some other testcase which require auto login
driver = new ChromeDriver();
driver.get("https://www.somesite.com");
// get store cookies and add them after refresh the page you will see user automatically get logged in
Set<Cookie> storeCookies = (Set<Cookie>) cookieMap.get("myCookies");
storeCookies.forEach(cookie -> driver.manage().addCookie(cookie));
driver.navigate().refresh();
请注意,我已将所有代码编写在单个文件中,您需要根据您的框架进行管理。例如,您所有的测试类都应该可以访问此Cookie映射。