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 {
/**
* @author gongjf
*/
public static void 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.xxx.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();
}
上面的代码首先在页面中增加了一个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 20xxxx -> /
www.xxx.com -> name -> value -> Tue Mar 12 17:33:00 CST 2030 -> /
www.xxxx.com -> PHPSESSID -> 51d37fc72eb0ea66e4ef1971b688698b -> null -> /
.51.com -> __utma -> 67913429.453585250.1331544776.1331544776.1331544776.1 -> Wed Mar 12 17:32:56 CST 20xxx -> /
www.xxx.com -> www_cookie_adv -> 1 -> Mon Mar 12 18:32:55 CST 20xxx -> /
.xxx.com -> __utmc -> 67913429 -> null -> /
www.51.com -> NSC_xxx -> 44595a553660 -> null -> /
.xxxx.com -> __utmb -> 67913429.1.10.1331544776 -> Mon Mar 12 18:02:56 CST 20xxx -> /
www.xxx.com -> www_jiaoyou_guide -> 0c83c0b5f569512d5a832bf0b4397a05 -> null -> /
网友评论