Webdriver+Java实现使用cookie跳过登录

时间:2023-12-25 12:34:13

Webdriver+Java实现使用cookie跳过登录

Webdriver模拟登录过程中很有可能遇到验证码,最近认真学习了下如何使用cookie直接跳过登录过程。

一、cookie的定义

来源百度百科:

Cookie,有时也用其复数形式 Cookies,指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)。定义于 RFC2109 和 2965 中的都已废弃,最新取代的规范是 RFC6265(可以叫做浏览器缓存)。

Cookie 是在 HTTP 协议下,服务器或脚本可以维护客户工作站上信息的一种方式。Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息。无论何时用户链接到服务器,Web 站点都可以访问 Cookie 信息 。

目前有些 Cookie 是临时的,有些则是持续的。临时的 Cookie 只在浏览器上保存一段规定的时间,一旦超过规定的时间,该 Cookie 就会被系统清除。持续的 Cookie 则保存在用户的 Cookie 文件中,下一次用户返回时,仍然可以对它进行调用。

临时的Cookie 是个存储在浏览器目录的文本文件,当浏览器运行时,存储在 RAM 中。当访客结束其浏览器对话时,即终止的所有 Cookie。持续的Cookie 可存储在计算机的硬驱上。

二、cookie的组成

一个cookie一般包括name,value,domain,path,expiry,isSecure。

简单实例如下:

Set-Cookie: name = VALUE;

expires = DATE;

path = PATH;

domain = DOMAIN_NAME;

三、使用Webdriver模拟登录后,将cookie写入cookie.data文件中,再次从文件中读取后跳过登录,具体代码如下:

 package XXX;

 import XXX;

 public class CookieTest implements Serializable{

 /**
 * 序列化
 */
 private static final long serialVersionUID = 1L;

 private WebDriver driver;
 private String baseUrl;
 private String homeUrl;
 private String cookiePath;
 private boolean acceptNextAlert = true;
 private StringBuffer verificationErrors = new StringBuffer();

 @Before
 /*
 * 方法名 setUp()
 * 加载chrome浏览器的驱动文件
 * 初始化chrome浏览器配置信息
 * 设置默认访问baseUrl = "XXXXXX";
 */
 public void setUp() throws Exception {
 System.setProperty("webdriver.chrome.driver","lib\\chromedriver_new.exe");
 ChromeOptions options = new ChromeOptions();
 options.addArguments("--start-maximized");// 让Chrome浏览器窗口最大化
 options.addArguments("--disable-popup-blocking");
 options.addArguments("no-sandbox");
 options.addArguments("disable-extensions");
 options.addArguments("no-default-browser-check");
 Map<String, Object> prefs = new HashMap<String, Object>();
 prefs.put("credentials_enable_service", false);
 prefs.put("profile.password_manager_enabled", false);
 options.setExperimentalOption("prefs", prefs);

 driver = new ChromeDriver(options);
 baseUrl = "XXXXXX";
 homeUrl = baseUrl+"XXXXXX";
 cookiePath = "cookie.data";
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }

 @Test
 public void saveCookieTest() throws FileNotFoundException, InterruptedException, IOException{
 //saveCookieNew("XXX","XXXX","cookie.data");
 getCookieLogin(homeUrl,cookiePath);
 }

 @SuppressWarnings("deprecation")
 public void getCookieLogin(String url,String cookiePath){
 driver.get(url);
 sleep(3000);
 File file = new File(cookiePath);
 try {
 FileReader fr = new FileReader(file);
 BufferedReader br = new BufferedReader(fr);
 String line;
 while((line = br.readLine())!= null){
 StringTokenizer st = new StringTokenizer(line,";");
 while(st.hasMoreTokens()){
 String name = st.nextToken();
 //System.out.println("name:"+name);//for test
 String value = st.nextToken();
 //System.out.println("value:"+value);//for test
 String domain = st.nextToken();
 //System.out.println("domain:"+domain);//for test
 String path = st.nextToken();
 //System.out.println("path:"+path);//for test
 Date expiry = null;//cookie的失效时间,默认存在浏览器打开期间
 String expiryString = st.nextToken();
 /*if(!(expiryString.equals(null)&& expiryString.equals("false")))
 {
 //expiry = new Date(expiryString);
 System.out.println("expiry:"+expiryString);//for test
 }*/
 boolean isSecure = new Boolean(st.nextToken()).booleanValue();
 //System.out.println("isSecure:"+isSecure);//for test

 Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
 //System.out.println(ck.toString());//for test
 driver.manage().addCookie(ck);
 }
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 driver.get(url);
 sleep(60000);
 }

 /**
 * 分别打印cookie信息
 * 使用BufferedWriter和FileWriter对象保存cookies到指定文件中
 * 保存格式:name;value;domain;expires;isSecure
 * @param username
 * @param password
 * @param cookiepath
 * @throws IOException
 */
 public void saveCookieNew(String username,String password,String cookiepath) {
 driver.get(baseUrl+"XXXXXX");
 sleep(1000);
 driver.findElement(By.id("userName")).clear();
 driver.findElement(By.id("userName")).sendKeys(username);
 sleep(1000);
 driver.findElement(By.id("password")).clear();
 driver.findElement(By.id("password")).sendKeys(password);
 sleep(2000);
 driver.findElement(By.xpath("//button[@type='button']")).click();
 sleep(5000);
 //driver.get(baseUrl+"ExerciseBookManager/web/home");

 //获取cookies
 Set<Cookie> cookies = driver.manage().getCookies();
 System.out.println("cookie_size:"+cookies.size());
 Iterator<Cookie> it = cookies.iterator();
 File file = new File(cookiepath);
 file.delete();
 try {
 file.createNewFile();
 FileWriter fw = new FileWriter(file);
 BufferedWriter bw = new BufferedWriter(fw);
 for(Cookie ck : cookies){
 bw.write(ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure());
 bw.newLine();
 }
 bw.flush();
 bw.close();
 fw.close();

 } catch (IOException e) {
 e.printStackTrace();
 }

 }

 /**
 * 分别打印cookie信息
 * 使用ObjectOutputStream和FileOutputStream对象保存cookies到指定文件中
 * @param username
 * @param password
 * @param savecookiepath
 * @throws InterruptedException
 * @throws FileNotFoundException
 * @throws IOException
 */
 public void saveCookie(String username,String password,String savecookiepath) throws InterruptedException, FileNotFoundException, IOException {
 driver.get(baseUrl+"ExerciseBookManager/web/auth/login");
 Thread.sleep(1000);
 driver.findElement(By.id("userName")).clear();
 driver.findElement(By.id("userName")).sendKeys(username);
 Thread.sleep(1000);
 driver.findElement(By.id("password")).clear();
 driver.findElement(By.id("password")).sendKeys(password);
 Thread.sleep(1000);
 driver.findElement(By.xpath("//button[@type='button']")).click();
 Thread.sleep(5000);
 //driver.get(baseUrl+"ExerciseBookManager/web/home");

 //获取cookies
 Set<Cookie> cookies = driver.manage().getCookies();
 System.out.println("cookie_size:"+cookies.size());
 Iterator<Cookie> it = cookies.iterator();
 CookieStore cookieStore = new BasicCookieStore();
 while(it.hasNext()){
 Cookie cookie = it.next();
 BasicClientCookie bcs = new BasicClientCookie(cookie.getName(),cookie.getValue());
 bcs.setDomain(cookie.getDomain());
 bcs.setPath(cookie.getPath());
 System.out.println(cookie.toString());
 cookieStore.addCookie(bcs);
 }
 //将Cookies保存到文件中
 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(savecookiepath)));
 oos.writeObject(cookieStore);
 oos.close();
 }

 @After
 public void tearDown() throws Exception {
 driver.quit();//关闭浏览器
 String verificationErrorString = verificationErrors.toString();
 if (!"".equals(verificationErrorString)) {
 fail(verificationErrorString);
 }
 }

 //等待时间
 public void sleep(long time){
 try {
 Thread.sleep(time);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }