
介绍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();
}
}