WebDriver 提供了一系列 Cookies 的操作来获取、填写、删除 Cookies 的方法,节省了多次在登陆页面的查找元素并填写登录信息的时间。
1)获取 Cookies ,并保存到文件中以备后续使用:
package com.learningselenium.normalwebdriver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Webdriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testGetCookies{
public static void main(String... args){
WebDriver driver = new FirefoxDriver();
driver.get("http://zhizhu.com/#signin");
//填写用户信息,然后登陆
driver.findElement(By.name("email")).sendKeys("seleniumcookies@126.com");
driver.findElement(By.name("password").sendKeys("cookies123"));
if(driver.findElement(By.name("rememberme")).isSelected()){
driver.findElement(By.name("remermberme")).click();
}
driver.findElement(By.className("sign-button")).click();
File cookieFile = new File("zhizhu.cookie.txt");
try{
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.getDomain() + ";" + cookie.getExpiry() + ";" + cookie.isSecure()));
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}catch (Exception ex){
ex.printStackTrace();
}
driver.quit();
}
}
2)读取保存的Cookies 信息并自动填充到新打开的浏览器 Cookies 中,然后直接进入登陆状态后的页面
public class testAddCookies{
private static BufferedReader bufferedReader;
public static void main(String... args){
WebDriver driver = new FirefoxDriver();
driver.get("http://zhizhu.com/#signin");
try{
File cookieFile = new File("zhihu.cookie.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()).booleanVaue();
Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("http://www.zhihu.com");
}