Webdriver+Java实现使用cookie跳过登录
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();
}
}
Webdriver+Java实现使用cookie跳过登录的更多相关文章
- Cookie跳转登录验证码
对于web应用来说,大部分的系统在用户登录时都要求用户输入验证码,验证码的类型的很多,有字母数字的,有汉字的,甚至还要用户输入一条算术题的答案的, 对于系统来说使用验证码可以有效果的防止采用机器猜测方 ...
- 自动化测试 -- 通过Cookie跳过登录验证码
之前写过一篇博客:自动化测试如何解决验证码的问题. http://www.cnblogs.com/fnng/p/3606934.html 介绍了验证码的几种处理方式,最后一种就是通过Cookie跳转过 ...
- python通过Cookie跳过登录验证码
1.通过浏览器获取登录cookie,找到重要的两个参数“BAIDUID”和“BDUSS”: 2.编写Selenium自动化测试脚本,跳过登录. from selenium import webdriv ...
- 通过Cookie跳过登录验证码【限cookie不失效有用】
验证码,相信每个写web自动化测试的同学来说,都是个头疼的事,怎么办呢? 方法还是有的,先说今天这种方式,通过cookie绕过登录验证码 思路: 需要你通过抓包工具抓到你登录的cookie 接下来开始 ...
- 【vue】axios + cookie + 跳转登录方法
axios 部分: import axios from 'axios' import cookie from './cookie.js' // import constVal from './cons ...
- Asp.net MVC访问框架页中嵌套的iframe页面时,如果session或cookie过期,登录验证超时怎样自动跳转到登录页
一般登录验证的过滤器中,使用验证过滤器的Redirect方法,将请求重定向到指定的URL.但是如果我们要访问的页面是一个嵌套在框架页中的iframe页面时,这种重定向只会对iframe页面凑效,也就是 ...
- selenium2 Webdriver + Java 自动化测试实战和完全教程
selenium2 Webdriver + Java 自动化测试实战和完全教程一.快速开始 博客分类: Selenium-webdriverselenium webdriver 学习selenium ...
- 《手把手教你》系列技巧篇(六十四)-java+ selenium自动化测试 - cookie -中篇(详细教程)
1.简介 今天按照原计划宏哥要用实例来给小伙伴或童鞋们来演示一下,如何利用cookie实现跳过验证码进行登录.这个场景是自动登陆.有很多系统的登陆信息都是保存在cookie里的,因此只要往cookie ...
- java和Discuz论坛实现单点登录,通过Ucenter(用户管理中心)
标题有点问题,没有进行修改. 一 Discuz论坛搭建步骤 1:服务器环境配置 服务器要支持php语言+支持mysql 5.0以上的数据库 + Apache服务器(支持网站的一个服务器,通过域名的能访 ...
随机推荐
- mpush 服务器环境配置安装 CentOS 7 and Windows
github-doc https://github.com/mywiki/mpush-doc/blob/master/SUMMARY.md Introduction 1.服务器环境 2.安装Redis ...
- 栈实现getMin
题目 实现一个特殊的栈,在实现栈的基本功能的基础上,在实现返回栈中最小元素的操作. 要求 pop.push.getMin操作的时间复杂度都是O(1). 设计的栈类型可以使用现成的栈结构. 解答 在设计 ...
- clamav 杀毒软件安装及使用配置
安装clamav 之前还需要安装zlib 要不然安装过程中会报错的. tar -zxvf zlib-1.2.3.tar.gz cd zlib-1.2.3 ./configure make make ...
- 使用CSharp编写Google Protobuf插件
什么是 Google Protocol Buffer? Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 ...
- phpcms基础
CSM基础(做中小型企业网站) 做一个企业站,三个页面比较重要1.首页2.列表页3.内容页 做企业站的流程:1.由美工出一张,设计效果图2.将设计图静态化3.开始安装CMS4.强模板文件放到CSM里面 ...
- 随机抽样一致算法(Random sample consensus,RANSAC)
作者:桂. 时间:2017-04-25 21:05:07 链接:http://www.cnblogs.com/xingshansi/p/6763668.html 前言 仍然是昨天的问题,别人问到最小 ...
- HTML5 进阶系列:indexedDB 数据库
前言 在 HTML5 的本地存储中,有一种叫 indexedDB 的数据库,该数据库是一种存储在客户端本地的 NoSQL 数据库,它可以存储大量的数据.从上篇:HTML5 进阶系列:web Stora ...
- 微信小程序后台音乐播放注意事项
wx.seekBackgroundAudio(OBJECT) 作用:控制音乐播放进度. 注意: 该事件 会触发 wx.onBackgroundAudioPlay(CALLBACK) 事件 ,也就是相当 ...
- file_get_contents url
file_get_contents (PHP 4 >= 4.3.0, PHP 5) file_get_contents — 将整个文件读入一个字符串 说明¶ string file_get_co ...
- linux 下创建管理员权限账户
1.添加用户,首先用adduser命令添加一个普通用户,命令如下: #adduser tommy //添加一个名为tommy的用户 #passwd tommy //修改密码 Changing pass ...