介绍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相关操作的更多相关文章

  1. 2.19 cookie相关操作

    2.19 cookie相关操作 前言虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录.登录后换账号登录时候,也可作 ...

  2. 《手把手教你》系列技巧篇(二十九)-java+ selenium自动化测试- Actions的相关操作上篇(详解教程)

    1.简介 有些测试场景或者事件,Selenium根本就没有直接提供方法去操作,而且也不可能把各种测试场景都全面覆盖提供方法去操作.比如:就像鼠标悬停,一般测试场景鼠标悬停分两种常见,一种是鼠标悬停在某 ...

  3. 《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)

    1.简介 本文主要介绍两个在测试过程中可能会用到的功能:Actions类中的拖拽操作和Actions类中的划取字段操作.例如:需要在一堆log字符中随机划取一段文字,然后右键选择摘取功能. 2.拖拽操 ...

  4. 《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)

    1.简介 上一篇中,宏哥说的宏哥在最后提到网站的反爬虫机制,那么宏哥在自己本地做一个网页,没有那个反爬虫的机制,谷歌浏览器是不是就可以验证成功了,宏哥就想验证一下自己想法,于是写了这一篇文章,另外也是 ...

  5. Selenium WebDriver 处理cookie

    在使用webdriver测试中,很多地方都使用登陆,cookie能够实现不必再次输入用户名密码进行登陆. 首先了解一下Java Cookie类的一些方法. 在jsp中处理cookie数据的常用方法: ...

  6. Django cookie相关操作

    Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...

  7. selenium webdriver模拟鼠标键盘操作

    在测试使用Selenium webdriver测试WEB系统的时候,用到了模拟鼠标.键盘的一些输入操作. 1.鼠标的左键点击.双击.拖拽.右键点击等: 2.键盘的回车.回退.空格.ctrl.alt.s ...

  8. selenium - webdriver - Keys类(键盘操作)

    Keys()类提供了键盘上几乎所有按键的方法,这个类可用来模拟键盘上的按键,包括各种组合键,如 Ctrl+A, Ctrl+X,Ctrl+C, Ctrl+V 等等 from selenium impor ...

  9. selenium - webdriver - ActionChains类(鼠标操作)

    ActionChains 类提供了鼠标操作的常用方法: perform(): 执行所有 ActionChains 中存储的行为: context_click(): 右击: double_click() ...

随机推荐

  1. Sublime Text使用手记

    1.Package Control 输入python 命令安装,打开控制台输入下方代码运行即可.控制台打开可使用快捷键Ctrl+~ 或菜单栏中View> Show Console,可访问Pack ...

  2. Javascript中数组方法汇总

    Array.prototype中定义了很多操作数组的方法,下面介绍ECMAScript3中的一些方法: 1.Array.join()方法 该方法将数组中的元素都转化为字符串并按照指定符号连接到一起,返 ...

  3. 对REST的一些理解

    昨天学习REST,发现有篇文章写的真心不错,看了一遍,并没有完全理解,将一些感觉比较重要的做个记录.  文章链接:REST简介 定义 Representational State Transfer ( ...

  4. MySQL的多实例

    一.准备工作     1.关闭mysql进程     # pkill     # service mysqld stop         2.从系统服务中删除mysqld     # chkconfi ...

  5. MySql中常用语句

    1.查询语句: SELECT  查询字段  FROM  表名   WHERE 条件 查询字段可以使用 通配符* 字段名 别名(把长的名字命名一个别名,比较短的) 通配符:SELECT * FROM ' ...

  6. Log4j 密码屏蔽

    Log4j filter to mask Payment Card numbers (PCI DSS) According to PCI DSS (Payment Card Industry Data ...

  7. sqlsever2008数据库的备份与还原

    本文数据库的名称为ProjectControl  public static SqlConnection conn = new SqlConnection("server=(local);u ...

  8. 黑马程序员-------.net基础知识四

    常量(静态常量------compile-time) 语法:const 类型 常量名 =常量值: 例: [csharp] view plaincopyprint? { const double PI= ...

  9. iOS - 应用程序国际化

    开发的移动应用更希望获取更多用户,走向世界,这就需要应用国际化,国际化其实就是多语言.这篇文章介绍Xcode4.5以后的国际化,包括应用名国际化和应用内容国际化.如果是Xcode4.5之前版本请参考. ...

  10. asp.net viewstate的模拟登陆

    其实 VIEWSTATE 不用太在意,倒是 JTCookieID 需要注意,这个才应该是服务器上用来维护 Session 的那个 Cookie.所以,你用 httpclient 的时候,不能上来就直接 ...