Web 测试中我们经常会接触到Cookies,一个Cookies主要属性有”所在域、name、value、有效日期和路径",下面来讲一下怎么操作Cookies。
- import java.util.Set;
-
- import org.openqa.selenium.Cookie;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
-
- public class CookiesStudy {
-
-
- public static void main(String[] args) {
-
- System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- WebDriver dr = new FirefoxDriver();
- dr.get("http://www.51.com");
-
-
- Cookie cookie = new Cookie("name", "value");
- dr.manage().addCookie(cookie);
-
-
- 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()));
-
-
-
-
-
- dr.manage().deleteCookieNamed("CookieName");
-
- dr.manage().deleteCookie(cookie);
-
- dr.manage().deleteAllCookies();
- }
上面的代码首先在页面中增加了一个cookie,然后遍历页面的所有cookies,并输出他们的主要属性。最后就是三种删除cookie的方法。遍历cookies输出的结果:
- 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 Sep 11 05:32:56 CST 2012 -> /
- www.51.com -> name -> value -> Tue Mar 12 17:33:00 CST 2030 -> /
- www.51.com -> PHPSESSID -> 51d37fc72eb0ea66e4ef1971b688698b -> null -> /
- .51.com -> __utma -> 67913429.453585250.1331544776.1331544776.1331544776.1 -> Wed Mar 12 17:32:56 CST 2014 -> /
- www.51.com -> www_cookie_adv -> 1 -> Mon Mar 12 18:32:55 CST 2012 -> /
- .51.com -> __utmc -> 67913429 -> null -> /
- www.51.com -> NSC_xxx -> 44595a553660 -> null -> /
- .51.com -> __utmb -> 67913429.1.10.1331544776 -> Mon Mar 12 18:02:56 CST 2012 -> /
- www.51.com -> www_jiaoyou_guide -> 0c83c0b5f569512d5a832bf0b4397a05 -> null -> /