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服务器(支持网站的一个服务器,通过域名的能访 ...
随机推荐
- List分组 用于客服对话分组场景
工作用可能会用到会话分组: Message是消息实体对象,里面有toId和fromId 指明接收方ID和发送方Id,通过组合形式"12-22-" 为map的key public M ...
- React-Native 之 项目实战(五)
前言 本文 有配套视频,可以酌情观看. 文中内容因各人理解不同,可能会有所偏差,欢迎朋友们联系我讨论. 文中所有内容仅供学习交流之用,不可用于商业用途,如因此引起的相关法律法规责任,与我无关,如文中内 ...
- Asp.net Authorization 学习
其实使用新的Identity以来一直有一个疑惑,之前的角色管理 在新的Identity中怎么管理的.[AspNetUserClaims] 在新的授权管理中又占什么位置 第一,根据角色授权,刚刚注册的用 ...
- 由CODEVS笨小猴1053引发的一些思考
#include<cstdio> #include<cstring> ]; ]; int check(int n) { ||n==) ; ;m*m<=n;++m) ) ; ...
- DFB系列 之 SetCooperativeLevel协作级别
1. 函数原型解析 函数声明 function SetCooperativeLevel(hWnd: HWND; dwFlags: DWORD): HResult; stdcall; 设置指定的IDir ...
- css优先级之特殊性
在前端开发的时候,css构建样式规则,这个时候我们会遇到一个问题:当我们对同一个元素做多个样式规则,其中发生了冲突的时候,css是如何选择最终呈现的样式 如下: div{ color:red; } d ...
- poj1990树状数组
Every year, Farmer John's N (1 <= N <= 20,000) cows attend "MooFest",a social gather ...
- 在Android Studio上测试运行,Unity发布成Android包过程中所遇到的问题及解决方案
问题一:Exception: JNI: Init'd AndroidJavaObject with null ptr 解决方法: 所有关于JNI出现的问题,只有三种错误存在,第一是需要在真机上运行测试 ...
- SectionIndexer 利用系统的控件,制作比较美观的侧栏索引控件
如上图所示,右侧的索引是系统提供的,具体使用方法,请搜索: SectionIndexer 相关的资料进行开发.
- Windows上Ruby开发环境的配置
最近公司项目上有需要,需要开发一个puppet的自动化工具,这个工具需要操作存储设备上的各种资源,而鉴于puppet不是善于完成这个任务的首选语言,于是我们选择了puppet的“爹”,Ruby. 熟悉 ...