|
Web 测试中我们经常会接触到Cookies,一个Cookies主要属性有”所在域、name、value、有效日期和路径”,下面来讲一下怎么操作Cookies。
CODE:
- <font size="4">import java.util.Set;
-
- import org.openqa.selenium.Cookie;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
-
- public class CookiesStudy {
-
- /**
- * @author gongjf
- */
- publicstaticvoid main(String[] args) {
- // TODO Auto-generated method stub
- System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- WebDriver dr = new FirefoxDriver();
- dr.get("http://www.51.com");
-
- //增加一个name = "name",value="value"的cookie
- Cookie cookie = new Cookie("name", "value");
- dr.manage().addCookie(cookie);
-
- //得到当前页面下所有的cookies,并且输出它们的所在域、name、value、有效日期和路径
- Set<Cookie> cookies = dr.manage().getCookies();
- System.out.println(String.format("Domain -> name -> value -> expiry -> path"));
- for(Cookie c : cookies)
- System.out.println(String.format("%s -> %s -> %s -> %s -> %s",
- c.getDomain(), c.getName(), c.getValue(),c.getExpiry(),c.getPath()));
-
-
- //删除cookie有三种方法
-
- //第一种通过cookie的name
- dr.manage().deleteCookieNamed("CookieName");
- //第二种通过Cookie对象
- dr.manage().deleteCookie(cookie);
- //第三种全部删除
- dr.manage().deleteAllCookies();
- }</font>
复制代码 上面的代码首先在页面中增加了一个cookie,然后遍历页面的所有cookies,并输出他们的主要属性。最后就是三种删除cookie的方法。遍历cookies输出的结果:
CODE:
- <font size="4">Domain -> name -> value -> expiry -> path
- .51.com -> FO_RFLP -> %7CaHR0cDovL3d3dy41MS5jb20v%7C%7C%7C ->null -> /
- .51.com -> __utmz ->67913429.1331544776.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) -> Tue Sep1105:32:56 CST2012 -> /
- www.51.com -> name -> value -> Tue Mar1217:33:00 CST2030 -> /
- www.51.com -> PHPSESSID -> 51d37fc72eb0ea66e4ef1971b688698b ->null -> /
- .51.com -> __utma ->67913429.453585250.1331544776.1331544776.1331544776.1 -> Wed Mar12 17:32:56 CST2014 -> /
- www.51.com -> www_cookie_adv ->1 -> Mon Mar1218:32:55 CST2012 -> /
- .51.com -> __utmc ->67913429 ->null -> /
- www.51.com -> NSC_xxx -> 44595a553660 ->null -> /
- .51.com -> __utmb ->67913429.1.10.1331544776 -> Mon Mar1218:02:56 CST2012 -> /
- www.51.com -> www_jiaoyou_guide -> 0c83c0b5f569512d5a832bf0b4397a05 ->null -> /</font>
复制代码
|
|