在使用webdriver测试中,很多地方都使用登陆,cookie能够实现不必再次输入用户名密码进行登陆。

首先了解一下Java Cookie类的一些方法。

在jsp中处理cookie数据的常用方法:
getDomain();返回cookie的域名.
getMaxAge();返回cookie的存活时间
getName();返回cookie的名字
getPath();返回cookie适用的路径
getSecure();如果浏览器通过安全协议发送Cookie将返回true值,如果浏览器使用标准协议刚返回false值
getValue();返回cookie的值
getVersion();返回cookie所遵从的协议版本setComment(String purpose);设置cookie的注释
setPath(String url);设置Cookie的适用路径
setSecure(Boolean flag);设置浏览器是否仅仅使用安全协议来发送cookie,例如使用Https或ssl
setValue(String newvalue);cookie创建后设置一个新的值
setVersion(int v);设置cookie所遵从的协议版本
selenium WebDriver 通过driver.manage().getCookies() 和driver.manage().addCookie(ck); 获取cookie 加载cookie
 
 
首先,获取cookie 保存的browser.data内
package com.packt.webdriver.chapter3;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Cookie; public class Cookies {
/**
* @author Young
*
*/
public static void addCookies() { WebDriver driver = DriverFactory.getChromeDriver();
driver.get("http://www.zhihu.com/#signin");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement user = driver
.findElement(By.xpath("//input[@name='email']"));
user.clear();
user.sendKeys("seleniumcookies@126.com");
WebElement password = driver.findElement(By
.xpath("//input[@name='password']"));
password.clear();
password.sendKeys("cookies123"); WebElement submit = driver.findElement(By
.xpath("//button[@class='sign-button']"));
submit.submit(); try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} File file = new File("broswer.data");
try {
// delete file if exists
file.delete();
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (Cookie ck : driver.manage().getCookies()) {
bw.write(ck.getName() + ";" + ck.getValue() + ";"
+ ck.getDomain() + ";" + ck.getPath() + ";"
+ ck.getExpiry() + ";" + ck.isSecure());
bw.newLine();
}
bw.flush();
bw.close();
fw.close(); } catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("cookie write to file");
}
}
}

这里,我简单封装了chrome webdriver

import java.util.Arrays;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities; public class DriverFactory { public static WebDriver create() { // TODO Auto-generated method stub
String chromdriver="E:\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromdriver);
ChromeOptions options = new ChromeOptions(); DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches",
Arrays.asList("--start-maximized"));
options.addArguments("--test-type", "--start-maximized");
WebDriver driver=new ChromeDriver(options);
return driver;
} }

接下来 ,读取browser.data,生成cookie  把cookie加载到浏览器

package com.packt.webdriver.chapter3;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader; import java.util.Date;
import java.util.StringTokenizer; import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.os.WindowsUtils; public class UseCookieLogin { /**
* @author Young
* @param args
*/ public static void main(String[] args) {
// TODO Auto-generated method stub
Cookies.addCookies();
WindowsUtils.tryToKillByName("chrome.exe");
WindowsUtils.getProgramFilesPath();
WebDriver driver=DriverFactory.getChromeDriver();
driver.get("http://www.zhihu.com/");
try
{
File file=new File("broswer.data");
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!= null)
{
StringTokenizer str=new StringTokenizer(line,";");
while(str.hasMoreTokens())
{
String name=str.nextToken();
String value=str.nextToken();
String domain=str.nextToken();
String path=str.nextToken();
Date expiry=null;
String dt;
if(!(dt=str.nextToken()).equals(null))
{
//expiry=new Date(dt);
System.out.println();
}
boolean isSecure=new Boolean(str.nextToken()).booleanValue();
Cookie ck=new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
}
} }
catch(Exception e)
{
e.printStackTrace();
} driver.get("http://www.zhihu.com/");
} }

再次打开之后,就是登陆后的页面

 

Selenium WebDriver 处理cookie的更多相关文章

  1. selenium webdriver(6)---cookie相关操作

    介绍selenium操作cookie之前,先简单介绍一下cookie的基础知识 cookie cookie一般用来识别用户身份和记录用户状态,存储在客户端电脑上.IE的cookie文件路径(win7) ...

  2. Selenium WebDriver对cookie进行处理绕过登录验证码

    现在几乎所有登录页面都会带一个验证码,做起自动化这块比较麻烦, 所以要绕过网站的验证码. 首先需要手动登录一次你的测试网站,去chrome的F12里获取这个网站的cookie信息,找到对应的保存登录信 ...

  3. Selenium WebDriver 对Cookie进行处理绕过登录验证码

    首先需要手动登录一次你的测试网站,去Chrome的F12中获取这个网站的cookie信息,找到对应的保存登录信息的cookie,接下来在代码中将上述的cookie信息通过webdriver写入的自动化 ...

  4. selenium webdriver 如何添加cookie

    一. webdriver中常用的cookie方法 webdriver中提供了操作cookie的相关方法: get_cookies()                  获得cookie信息 add_c ...

  5. selenium webdriver处理浏览器Cookie

    有时候我们需要验证浏览器中是否存在某个cookie,因为基于真实的cookie 的测试是无法通过白盒和集成测试完成的.WebDriver 提供了操作Cookie 的相关方法可以读取.添加和删除cook ...

  6. selenium - webdriver - cookie操作

    WebDriver提供了操作Cookie的相关方法,可以读取.添加和删除cookie信息. WebDriver操作cookie的方法: get_cookies(): 获得所有cookie信息. get ...

  7. selenium webdriver如何添加cookie

    一. webdriver中常用的cookie方法 webdriver中提供了操作cookie的相关方法: get_cookies()                  获得cookie信息 add_c ...

  8. Selenium_用selenium webdriver实现selenium RC中的类似的方法

    最近想总结一下学习selenium webdriver的情况,于是就想用selenium webdriver里面的方法来实现selenium RC中操作的一些方法.目前封装了一个ActionDrive ...

  9. selenium webdriver (python) 第二版

    前言 对于大多软件测试人员来讲缺乏编程经验(指项目开发经验,大学的C 语言算很基础的编程知识)一直是难以逾越的鸿沟,并不是说测试比开发人员智商低,是国内的大多测试岗位是功能测试为主,在工作时间中,我们 ...

随机推荐

  1. javascript 之Object内置对象

    Object.defineProperty(obj, prop, descriptor)

  2. Java学习注意事项

    一个Java文件中可以包含多个类. 如果有public类,则文件名必须和public类一样. 例如: class Pie { void f(){ System.out.println("Pi ...

  3. twoSum

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  4. Linux下查看文件内容的命令

    查看文件内容的命令: cat     由第一行开始显示内容,并将所有内容输出 tac     从最后一行倒序显示内容,并将所有内容输出 more    根据窗口大小,一页一页的现实文件内容 less ...

  5. hdu4751 Divide Groups

    This year is the 60th anniversary of NJUST, and to make the celebration more colorful, Tom200 is goi ...

  6. DatePicker隐藏年月日

    1.隐藏年 ((ViewGroup) (((ViewGroup) dp.getChildAt(0)).getChildAt(0))) .getChildAt(0).setVisibility(View ...

  7. 用数组求Fibonacci数列

    #include<stdio.h>int main(){      int a[20]={1,1};      int n=2,i;      for(n=2;n<20;n++)  ...

  8. BeanFactory和ApplicationContext的区别

     1.BeanFactory和ApplicationContext的异同点: 相同点:     两者都是通过xml配置文件加载bean,ApplicationContext和BeanFacotry相比 ...

  9. Mac os壁纸提取

    想必用过Mac os系统的朋友都知道mac壁纸,提取出来用作壁纸是十分好看的 下面给出壁纸的位置,自己用文件管理器打开然后复制出来即可! 系统盘:/Library/DesktopPictures

  10. 关于sql用<>不等于查询数据不对问题

    平常查询数据 ' 当想要查询 不等于1 的数据的时候,一般会这样查询 ' 此处查询结果没查到所有想要的结果,如果night_flag 列数据为 null时,此行数据是查询不到的. 解决方法一: ' 解 ...