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 ...
- Java使用递归找出某目录下的所有子目录以及子文件
/* 使用递归找出某目录("C:\\JavaProducts")下的所有子目录以及子文件 */ import java.util.*; import java.io.*; publ ...
- vscode奇淫记(上)
每次换editor都是一种煎熬,从最早的eclipse,sublime,webstorm到现在在用的atom,换编辑器的驱动是寻找更酷炫和轻量的平衡点,其实我真的蛮喜欢atom的,酷炫!那我这次打算入 ...
- Asp .Net MVC4笔记之目录结构
认识MVC从目录结构开始,从基本创建开始. App_Data 文件夹:App_Data 文件夹用于存储应用程序数据. App_Start:启动文件的配置信息,包括很重要的RouteConfig路由注册 ...
- Centos下装eclipse测试Hadoop
(一),安装eclipse 1,下载eclipse,点这里 2,将文件上传到Centos7,可以用WinSCP 3,解压并安装eclipse [root@Master opt]# tar zxvf ' ...
- 关于String类和String[]数组的获取长度方法细节
一.在Java中,以下代码段有错误的是第( )行 public static void main(String[] args) { String name = "小新"; ...
- linux性能之iostat
在使用linux系统的过程中,总是可能需要当前io性能的状态信息是怎么样?这里就就是一下iostat,可以通过iostat来初步查看io的状态信息. 1.常用方式 iostat -xdk 1 10 或 ...
- AspNetCore-MVC实战系列(四)之结尾
AspNetCore - MVC实战系列目录 . 爱留图网站诞生 . git源码:https://github.com/shenniubuxing3/LovePicture.Web . AspNetC ...
- 被低估的选手 - JavaFx
被低估的选手 - JavaFx 1.MFC(Visual C++) 个人不是很喜欢这个框架,太多系统定义的东西,就像无底洞,学都学不完,这个东西需要你有比较强的记忆力,并且能融会贯通里面很多预定义的功 ...
- mysql获取当前日期的周一和周日的日期
,,date_format(curdate(),)//获取当前日期 在本周的周一 的日期 ,,date_format(curdate(),)//获取当前日期 在本周的周日 的日期