selenium测试(Java)--操作cookie(十七)

 

 1 package com.test.cookies;
 2 
 3 import org.openqa.selenium.Cookie;
 4 import org.openqa.selenium.JavascriptExecutor;
 5 import org.openqa.selenium.WebDriver;
 6 import org.openqa.selenium.firefox.FirefoxDriver;
 7 
 8 public class CookieOperation {
 9 
10     public static void main(String[] args) {
11 
12         WebDriver driver = new FirefoxDriver();
13         driver.get("http://www.baidu.com");
14         driver.manage().window().maximize();
15 
16         // 获取所有cookie个数
17         System.out.println(driver.manage().getCookies().size());
18 
19         // 增加cookie
20         Cookie cookie = new Cookie("username", "name", "/", null);
21         driver.manage().addCookie(cookie);
22         driver.manage().addCookie(new Cookie("password", "ppppwwww", "/", null));
23         
24         // 以name获取cookie
25         String name = driver.manage().getCookieNamed("username").getValue();
26         String info = "用户名是: " + name;
27         String js = "alert(\"" + info + "\");";
28         System.out.println(js);
29         ((JavascriptExecutor) driver).executeScript(js);
30 
31         waitTime(5000);
32         driver.switchTo().alert().dismiss();
33         
34         // 以name删除cookie
35         driver.manage().deleteCookieNamed("password");
36 
37         // 再次获取所有cookie个数,应该比之前多一个
38         System.out.println(driver.manage().getCookies().size());
39 
40         driver.quit();
41 
42     }
43 
44     static public void waitTime(int time) {
45 
46         try {
47             Thread.sleep(time);
48         } catch (InterruptedException e) {
49             // TODO Auto-generated catch block
50             e.printStackTrace();
51         }
52     }
53 }

 

执行结果:

8
alert("用户名是: name");
9

posted @ 2016-07-16 15:59  月色深潭  阅读(8058)  评论(4编辑  收藏  举报