selenium操作浏览器cookies
package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Date; import java.util.StringTokenizer; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import common.StartChrome; public class TestCookies { public static void main(String[] args) { TestCookies.getCookies(); TestCookies.addCookies(); } public static void addCookies(){ BufferedReader bufferedReader; // WebDriver driver = StartFireFox.start(); WebDriver driver=StartChrome.start(); driver.get("http://www.zhihu.com/"); try { File cookieFile = new File("zhizhu.txt"); FileReader fr=new FileReader(cookieFile); bufferedReader= new BufferedReader(fr); 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); driver.manage().addCookie(cookie); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); driver.get("http://www.zhihu.com"); } public static void getCookies(){ //WebDriver driver = StartFireFox.start(); WebDriver driver=StartChrome.start(); driver.get("https://www.zhihu.com/#signin"); //填写用户信息,然后登陆 driver.findElement(By.name("account")).sendKeys("XXXX"); driver.findElement(By.name("password")).sendKeys("XXXX"); if(driver.findElement(By.name("remember_me")).isSelected()){ driver.findElement(By.name("remember_me")).click(); } driver.findElement(By.className("sign-button")).click(); try{ Thread.sleep(3000); File cookieFile = new File("zhizhu.txt"); cookieFile.delete(); cookieFile.createNewFile(); FileWriter fileWriter = new FileWriter(cookieFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); for (Cookie cookie : driver.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 (Exception ex){ ex.printStackTrace(); } System.out.println("close brower"); driver.quit(); } }
重点保存cookies到一个文件,然后每次读取文件