描述:登录CSDN,将登录信息cookies保存到文件,再次打开网页时,直接利用文件中的数据登录。
1. 获取cookies并保存到文件
步骤:
① 打开CSDN的登录界面;
② 填写用户名和密码;
③ 新建文件txt;
④ 获取cookies,并将cookies保存到先前新建的文件中。
代码:
@Before public void Setup(){ File chromeDriverPath = new File("D:\Selenium\webdriver\chromedriver.exe"); System.setProperty("webdriver.chrome.driver", chromeDriverPath.getAbsolutePath()); webDriver = new ChromeDriver(); } @Test public void writeCookies() { webDriver.get("https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn"); webDriver.findElement(By.xpath("//*[@id="username"]")).sendKeys("用户名"); webDriver.findElement(By.xpath("//*[@id="password"]")).sendKeys("密码"); if (webDriver.findElement(By.xpath("//*[@id="rememberMe"]")).isSelected()){ webDriver.findElement(By.xpath("//*[@id="rememberMe"]")).click(); } webDriver.findElement(By.xpath("//*[@id="fm1"]/input[6]")).click(); File cookieFile = new File("csdn.cookie.txt"); try { cookieFile.delete(); cookieFile.createNewFile(); FileWriter fileWriter = new FileWriter(cookieFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); for (Cookie cookie:webDriver.manage().getCookies()){ bufferedWriter.write((cookie.getName()+";"+ cookie.getValue()+";"+ cookie.getDomain()+";"+ cookie.getPath()+";"+ cookie.getExpiry()+";"+ cookie.isSecure())); bufferedWriter.newLine(); } bufferedWriter.flush(); bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } webDriver.quit(); }
2. 读取先前文件中保存的信息,将信息添加到新建的cookie中,将新建的cookie添加到浏览器中,实现自动登陆。
步骤:
① 打开CSDN界面;
② 从保存的文件中取出登陆的信息,添加到cookie中,将cookie添加到浏览器中;
③ 打开CSDN界面。
代码:
@Test public void getCookies(){ BufferedReader bufferedReader; webDriver.get("https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn"); try { File cookieFile = new File("csdn.cookie.txt"); FileReader fileReader = new FileReader(cookieFile); bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null){ StringTokenizer stringTokenizer = new StringTokenizer(line, ";"); while (stringTokenizer.hasMoreTokens()){ String name = stringTokenizer.nextToken(); String value = stringTokenizer.nextToken(); String domain = stringTokenizer.nextToken(); String path = stringTokenizer.nextToken(); Date expiry = null; String dt; if (!(dt = stringTokenizer.nextToken()).equals("null")){ expiry = new Date(dt); } boolean isSecure = new Boolean(stringTokenizer.nextToken()).booleanValue(); Cookie cookie = new Cookie(name, value,domain,path,expiry,isSecure); webDriver.manage().addCookie(cookie); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } webDriver.get("http://blog.csdn.net/"); }
结果:状态直接变成登录状态。
(个人学习笔记,不对之处,多多指正,谢谢!)