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名称来获取
1 import java.util.Set; 2 import org.openqa.selenium.By; 3 import org.openqa.selenium.Cookie; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.chrome.ChromeDriver; 7 8 public class NewTest{ 9 public static void main(String[] args) throws InterruptedException { 10 System.setProperty ( "webdriver.chrome.driver" , 11 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); 12 WebDriver driver = new ChromeDriver(); 13 driver.get("http://localhost/cookie.html"); 14 15 //这两句不能省略 16 WebElement element=driver.findElement(By.xpath("//input[@id='1']")); 17 element.click(); 18 19 System.out.println(driver.manage().getCookieNamed("name")); 20 21 Thread.sleep(3000); 22 driver.quit(); 23 } 24 }
输出如下
和我们在页面中添加的cookie是一样的,第二种是通过selenium提供的Cookie类获取,接口中有云:
1 import java.util.Set; 2 import org.openqa.selenium.By; 3 import org.openqa.selenium.Cookie; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.chrome.ChromeDriver; 7 8 public class NewTest{ 9 public static void main(String[] args) throws InterruptedException { 10 System.setProperty ( "webdriver.chrome.driver" , 11 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); 12 WebDriver driver = new ChromeDriver(); 13 driver.get("http://localhost/cookie.html"); 14 15 //这两句不能省略 16 WebElement element=driver.findElement(By.xpath("//input[@id='1']")); 17 element.click(); 18 19 Set<Cookie> cookies=driver.manage().getCookies(); 20 21 System.out.println("cookie总数为"+cookies.size()); 22 23 for(Cookie cookie:cookies) 24 System.out.println("作用域:"+cookie.getDomain()+", 名称:"+cookie.getName()+ 25 ", 值:"+cookie.getValue()+", 范围:"+cookie.getPath()+ 26 ", 过期时间"+cookie.getExpiry()); 27 Thread.sleep(3000); 28 driver.quit(); 29 } 30 }
输出大概是这样子
添加cookie
添加cookie就很简单了
1 import java.util.Set; 2 import org.openqa.selenium.By; 3 import org.openqa.selenium.Cookie; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.chrome.ChromeDriver; 7 8 public class NewTest{ 9 public static void main(String[] args) throws InterruptedException { 10 System.setProperty ( "webdriver.chrome.driver" , 11 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); 12 WebDriver driver = new ChromeDriver(); 13 driver.get("http://localhost/cookie.html"); 14 15 //这两句不能省略 16 WebElement element=driver.findElement(By.xpath("//input[@id='1']")); 17 element.click(); 18 19 Cookie cookie=new Cookie("java","eclipse","/",null); 20 driver.manage().addCookie(cookie); 21 22 System.out.println(driver.manage().getCookieNamed("java")); 23 24 Thread.sleep(3000); 25 driver.quit(); 26 } 27 }
可以看到,我们先是生成了一个cookie实例,然后通过addCookie方法添加cookie.参数的含义可以在cookie类的定义中找到,位于org.openqa.selenium.Cookie,下面是其中的一个
删除cookie
有三种途径:
- deleteAllCookies 删除所有cookie
- deleteCookie 删除指定的cookie,参数一个cookie对象
- deleteCookieNamed 根据cookie名称删除
1 import java.util.Set; 2 import org.openqa.selenium.By; 3 import org.openqa.selenium.Cookie; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.chrome.ChromeDriver; 7 8 public class NewTest{ 9 public static void main(String[] args) throws InterruptedException { 10 System.setProperty ( "webdriver.chrome.driver" , 11 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); 12 WebDriver driver = new ChromeDriver(); 13 driver.get("http://localhost/cookie.html"); 14 15 //这两句不能省略 16 WebElement element=driver.findElement(By.xpath("//input[@id='1']")); 17 element.click(); 18 Cookie cookie=new Cookie("java","eclipse","/",null); 19 driver.manage().addCookie(cookie); 20 21 //删除名称为value的cookie 22 driver.manage().deleteCookieNamed("value"); 23 //删除刚才新增的cookie java 24 driver.manage().deleteCookie(cookie); 25 26 //输出现有cookie 27 Set<Cookie> cks=driver.manage().getCookies(); 28 System.out.println("cookie总数为"+cks.size()); 29 for(Cookie ck:cks) 30 System.out.println("作用域:"+ck.getDomain()+", 名称:"+ck.getName()+ 31 ", 值:"+ck.getValue()+", 范围:"+ck.getPath()+ 32 ", 过期时间"+ck.getExpiry()); 33 34 //删除全部cookie 35 driver.manage().deleteAllCookies(); 36 Set<Cookie> c=driver.manage().getCookies(); 37 System.out.println("cookie总数为"+c.size()); 38 39 Thread.sleep(3000); 40 driver.quit(); 41 } 42 }
说了这么多,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自动登录了(忽略了密码验证)
1 import org.openqa.selenium.Cookie; 2 import org.openqa.selenium.WebDriver; 3 import org.openqa.selenium.chrome.ChromeDriver; 4 5 public class NewTest{ 6 public static void main(String[] args) throws InterruptedException { 7 System.setProperty ( "webdriver.chrome.driver" , 8 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); 9 WebDriver driver = new ChromeDriver(); 10 driver.get("http://localhost/cookie.php"); 11 driver.manage().deleteAllCookies(); 12 Cookie cookie=new Cookie("username","eclipse","/",null); 13 driver.manage().addCookie(cookie); 14 Cookie cookie1=new Cookie("password","123@qq.com","/",null); 15 driver.manage().addCookie(cookie1); 16 driver.get("http://localhost/cookie.php"); 17 18 Thread.sleep(3000); 19 driver.quit(); 20 } 21 }