selenium webdriver(6)---cookie相关操作
介绍selenium操作cookie之前,先简单介绍一下cookie的基础知识
cookie
cookie一般用来识别用户身份和记录用户状态,存储在客户端电脑上。IE的cookie文件路径(win7):
"C:\Users\用户名\AppData\Roaming\Microsoft\Windows\Cookies"
如果windows下没有cookies文件夹,需要把隐藏受保护的系统文件夹前面的勾去掉;chrome的cookie路径(win7):
"C:\Users\用户名\AppData\Local\Google\Chrome\User Data\Default\Cookies"
IE把不同的cookie存储为不同的txt文件,所以每个文件都较小,chrome是存储在一个cookies文件中,该文件较大。
通过js操作cookie
可以通过如下方式添加方式
<html>
<head>
<title>cookie演示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript">
function addCookie(){
var date=new Date();
var expiresDays=1;
//将date设置为1天以后的时间
date.setTime(date.getTime()+expiresDays*24*3600*1000);
//name设置为1天后过期
document.cookie="name=cookie;expires="+date.toGMTString();
}
</script>
</head>
<body>
<input type="button" onclick="addCookie()" value="增加cookie">
</body>
</html>
IE浏览器会在上述文件夹下生成一个txt文件,内容即为刚才的键值对
chrome浏览器可以直接查看cookie,地址栏输入chrome://settings/content即可,注意过期时间是一天以后
想要获取cookie也很简单,把赋值语句倒过来写即可
<html>
<head>
<title>cookie演示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript">
function addCookie(){
var date=new Date();
var expiresDays=1;
//将date设置为1天以后的时间
date.setTime(date.getTime()+expiresDays*24*3600*1000);
//name设置为1天后过期
document.cookie="name=cookie;expires="+date.toGMTString(); var str=document.cookie;
//按等号分割字符串
var cookie=str.split("=");
alert("cookie "+cookie[0]+"的值为"+cookie[1]);
}
</script>
</head>
<body>
<input type="button" onclick="addCookie()" value="增加cookie">
</body>
</html>
cookie的删除采用设置cookie过期的方法,即把cookie的过期时间设置为过去的某个时间
<html>
<head>
<title>cookie演示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript">
function addCookie(){
var date=new Date();
var expiresDays=1;
//将date设置为1天以前的时间即可删除此cookie
date.setTime(date.getTime()-expiresDays*24*3600*1000);
//name设置为1天后过期
document.cookie="name=cookie;expires="+date.toGMTString(); var str=document.cookie;
//按等号分割字符串
var cookie=str.split("=");
alert("cookie "+cookie[0]+"的值为"+cookie[1]);
}
</script>
</head>
<body>
<input type="button" onclick="addCookie()" value="增加cookie">
</body>
</html>
selenium 操作cookie
有了上面的介绍再来看selenium操作cookie的相关方法就很好理解了,和js是一样的道理,先通过js添加两个cookie(兼容chrome)
<html>
<head>
<title>cookie演示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript">
function addCookie(){
var date=new Date();
var expiresDays=1;
//将date设置为1天以后过期
date.setTime(date.getTime()+expiresDays*24*3600*1000); document.cookie="name=test; path=/;expires="+date.toGMTString();
document.cookie="value=selenium; path=/;expires="+date.toGMTString();
var str=document.cookie;
var cookies=str.split(";");
for(var i=0;i<cookies.length;i++){
var cookie=cookies[i].split("=");
console.log("cookie "+cookie[0]+"的值为"+cookie[1]);
} }
</script>
</head>
<body>
<input type="button" id="1" onclick="addCookie()" value="增加cookie">
</body>
</html>
获得cookie
有两种方法可以获得cookie,第一种是直接通过cookie名称来获取
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver; public class NewTest{
public static void main(String[] args) throws InterruptedException {
System.setProperty ( "webdriver.chrome.driver" ,
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get("http://localhost/cookie.html"); //这两句不能省略
WebElement element=driver.findElement(By.xpath("//input[@id='1']"));
element.click(); System.out.println(driver.manage().getCookieNamed("name")); Thread.sleep(3000);
driver.quit();
}
}
输出如下
和我们在页面中添加的cookie是一样的,第二种是通过selenium提供的Cookie类获取,接口中有云:
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver; public class NewTest{
public static void main(String[] args) throws InterruptedException {
System.setProperty ( "webdriver.chrome.driver" ,
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get("http://localhost/cookie.html"); //这两句不能省略
WebElement element=driver.findElement(By.xpath("//input[@id='1']"));
element.click(); Set<Cookie> cookies=driver.manage().getCookies(); System.out.println("cookie总数为"+cookies.size()); for(Cookie cookie:cookies)
System.out.println("作用域:"+cookie.getDomain()+", 名称:"+cookie.getName()+
", 值:"+cookie.getValue()+", 范围:"+cookie.getPath()+
", 过期时间"+cookie.getExpiry());
Thread.sleep(3000);
driver.quit();
}
}
输出大概是这样子
添加cookie
添加cookie就很简单了
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver; public class NewTest{
public static void main(String[] args) throws InterruptedException {
System.setProperty ( "webdriver.chrome.driver" ,
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get("http://localhost/cookie.html"); //这两句不能省略
WebElement element=driver.findElement(By.xpath("//input[@id='1']"));
element.click(); Cookie cookie=new Cookie("java","eclipse","/",null);
driver.manage().addCookie(cookie); System.out.println(driver.manage().getCookieNamed("java")); Thread.sleep(3000);
driver.quit();
}
}
可以看到,我们先是生成了一个cookie实例,然后通过addCookie方法添加cookie.参数的含义可以在cookie类的定义中找到,位于org.openqa.selenium.Cookie,下面是其中的一个
删除cookie
有三种途径:
- deleteAllCookies 删除所有cookie
- deleteCookie 删除指定的cookie,参数一个cookie对象
- deleteCookieNamed 根据cookie名称删除
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver; public class NewTest{
public static void main(String[] args) throws InterruptedException {
System.setProperty ( "webdriver.chrome.driver" ,
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get("http://localhost/cookie.html"); //这两句不能省略
WebElement element=driver.findElement(By.xpath("//input[@id='1']"));
element.click();
Cookie cookie=new Cookie("java","eclipse","/",null);
driver.manage().addCookie(cookie); //删除名称为value的cookie
driver.manage().deleteCookieNamed("value");
//删除刚才新增的cookie java
driver.manage().deleteCookie(cookie); //输出现有cookie
Set<Cookie> cks=driver.manage().getCookies();
System.out.println("cookie总数为"+cks.size());
for(Cookie ck:cks)
System.out.println("作用域:"+ck.getDomain()+", 名称:"+ck.getName()+
", 值:"+ck.getValue()+", 范围:"+ck.getPath()+
", 过期时间"+ck.getExpiry()); //删除全部cookie
driver.manage().deleteAllCookies();
Set<Cookie> c=driver.manage().getCookies();
System.out.println("cookie总数为"+c.size()); Thread.sleep(3000);
driver.quit();
}
}
说了这么多,selenium来操作cookie到底有什么用呢?主要有两点:
1.测试web程序经常需要清楚浏览器缓存,以消除不同版本的影响,selenium就可以自动执行了,每次测试新版本前先清楚缓存文件
2.用来完成自动登陆的功能,无需再编写登录的公共方法了
现在有两个页面cookie.php为登录页面,login.php是登陆后跳转的页面,如果用户已经登录即已有用户的cookie就自动跳转到login.php.
cookie.php
<html>
<head>
<title>cookie演示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
if(isset($_COOKIE["username"])){
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href='login.php'";
echo "</script>";
}
?>
<form action="login.php" method="post">
<span>用户名:</span><input type="text" name="username" >
<br>
<span>密 码:</span><input type="password" name="password">
<br>
<input type="submit" name="submit" value="提交" onclick="addCookie()">
</form>
</body>
</html>
login.php
<?php
setcookie("username",$_POST["username"]);
setcookie("password",$_POST["password"]);
if(isset($_COOKIE["username"]))
echo $_COOKIE["username"];
else
echo $_POST["username"];
?>
可以这样写selenium,就可以用用户eclipse自动登录了(忽略了密码验证)
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; public class NewTest{
public static void main(String[] args) throws InterruptedException {
System.setProperty ( "webdriver.chrome.driver" ,
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" );
WebDriver driver = new ChromeDriver();
driver.get("http://localhost/cookie.php");
driver.manage().deleteAllCookies();
Cookie cookie=new Cookie("username","eclipse","/",null);
driver.manage().addCookie(cookie);
Cookie cookie1=new Cookie("password","123@qq.com","/",null);
driver.manage().addCookie(cookie1);
driver.get("http://localhost/cookie.php"); Thread.sleep(3000);
driver.quit();
}
}
selenium webdriver(6)---cookie相关操作的更多相关文章
- 2.19 cookie相关操作
2.19 cookie相关操作 前言虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录.登录后换账号登录时候,也可作 ...
- 《手把手教你》系列技巧篇(二十九)-java+ selenium自动化测试- Actions的相关操作上篇(详解教程)
1.简介 有些测试场景或者事件,Selenium根本就没有直接提供方法去操作,而且也不可能把各种测试场景都全面覆盖提供方法去操作.比如:就像鼠标悬停,一般测试场景鼠标悬停分两种常见,一种是鼠标悬停在某 ...
- 《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)
1.简介 本文主要介绍两个在测试过程中可能会用到的功能:Actions类中的拖拽操作和Actions类中的划取字段操作.例如:需要在一堆log字符中随机划取一段文字,然后右键选择摘取功能. 2.拖拽操 ...
- 《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)
1.简介 上一篇中,宏哥说的宏哥在最后提到网站的反爬虫机制,那么宏哥在自己本地做一个网页,没有那个反爬虫的机制,谷歌浏览器是不是就可以验证成功了,宏哥就想验证一下自己想法,于是写了这一篇文章,另外也是 ...
- Selenium WebDriver 处理cookie
在使用webdriver测试中,很多地方都使用登陆,cookie能够实现不必再次输入用户名密码进行登陆. 首先了解一下Java Cookie类的一些方法. 在jsp中处理cookie数据的常用方法: ...
- Django cookie相关操作
Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...
- selenium webdriver模拟鼠标键盘操作
在测试使用Selenium webdriver测试WEB系统的时候,用到了模拟鼠标.键盘的一些输入操作. 1.鼠标的左键点击.双击.拖拽.右键点击等: 2.键盘的回车.回退.空格.ctrl.alt.s ...
- selenium - webdriver - Keys类(键盘操作)
Keys()类提供了键盘上几乎所有按键的方法,这个类可用来模拟键盘上的按键,包括各种组合键,如 Ctrl+A, Ctrl+X,Ctrl+C, Ctrl+V 等等 from selenium impor ...
- selenium - webdriver - ActionChains类(鼠标操作)
ActionChains 类提供了鼠标操作的常用方法: perform(): 执行所有 ActionChains 中存储的行为: context_click(): 右击: double_click() ...
随机推荐
- 《程序员的思维修炼》摘抄start:2014年9月27日19:27:07
程序员的思维修炼:摘抄:考虑到社会中各个相关团体的复杂交互影响和社会的持续变化,在我看来当前最重要的两项技能就是: ▪沟通能力: ▪学习和思考能力.软件行业正在逐步提高沟通能力.特别是敏捷方法(见注解 ...
- 14_输出映射2_resultMap
[resultMap] 如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间做一个映射列表. 1.定义resultMap,(在UserMapper.xm ...
- QT5新手上路(1)安装
这几天学了一下windows下的QT,也不算什么心得吧,就是谈一下我的做法.希望看到这篇随笔的菜鸟们略有所得,少走弯路. 闲话少说,先说安装.首先是选版本,我用的是qt-opensource-wind ...
- [翻译][MVC 5 + EF 6] 3:排序、过滤、分页
原文:Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application 1.添加排序: 1. ...
- win7下简单FTP服务器搭建
本文介绍通过win7自带的IIS来搭建一个只能实现基本功能的FTP服务器,第一次装好WIN7后我愣是没整出来,后来查了一下网上资料经过试验后搭建成功,其实原理和步骤与windows前期的版本差不多,主 ...
- nginx方面的书籍资料链接
http://tengine.taobao.org/book/ http://blog.sina.com.cn/s/articlelist_1929617884_0_1.html http://blo ...
- 让你的 Node.js 应用跑得更快的 10 个技巧
Node.js 受益于它的事件驱动和异步的特征,已经很快了.但是,在现代网络中只是快是不行的.如果你打算用 Node.js 开发你的下一个Web 应用的话,那么你就应该无所不用其极,让你的应用更快,异 ...
- FusionCharts xml入门教程
由于项目需求需要做一个报表,选择FusionCharts作为工具使用.由于以 前没有接触过报表,网上也没有比较详细的fusionCharts教程,所以决定好好研究FusionCharts,同时做一个比 ...
- 如何利用C生成.so供Mono调用
Mono诞生的初衷是为了吸引更多的Windows .Net程序员来加入Linux平台的开发.但在Linux世界中C语言依然是 主流.很多时候一些关键应用(比如大型 笛卡儿 乘积运算.需要调用平台硬件功 ...
- POJ 1716 Integer Intervals 差分约束
题目:http://poj.org/problem?id=1716 #include <stdio.h> #include <string.h> #include <ve ...