您的位置:軟件測(cè)試 > 開(kāi)源軟件測(cè)試 > 開(kāi)源功能測(cè)試工具 > Selenium
Selenium2操作瀏覽器的Cookies
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2016/3/10 14:32:43 ] 推薦標(biāo)簽:功能測(cè)試 軟件測(cè)試工具

  一、cookies廣泛應(yīng)用于web技術(shù)中,它伴隨用戶請(qǐng)求在web服務(wù)器和瀏覽器之間傳遞.....本文在selenium WebDriver中如何讀取瀏覽器的cookies以及如何在瀏覽器中使用已有的cookies 這兩個(gè)方面而展開(kāi)。
  二、首先,分析第一個(gè)問(wèn)題:WebDriver中如何讀取瀏覽器的cookies?WebDriver包中已封裝好關(guān)于Cookies的相關(guān)類和方法,通過(guò)WebDriver的manage().getCookies()方法
而獲取,詳見(jiàn)下面代碼:
File cookieFile = new File(COOKIE_PATH);
try {
if(cookieFile.exists()){
cookieFile.delete();
}
cookieFile.createNewFile();
System.out.println("Create a new cookie file in:"+System.getProperty("user.dir"));
//將當(dāng)前的cookies寫(xiě)入指定文件
BufferedWriter bWriter = new BufferedWriter(new FileWriter(cookieFile));
for(Cookie cookie : driver.manage().getCookies()){
bWriter.write(
cookie.getName() + "/"
+ cookie.getValue() + "/"
+ cookie.getPath() + "/"
+ cookie.getExpiry() + "/"
+ cookie.isSecure());
bWriter.newLine();
}
bWriter.flush();
bWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
  三、模擬繞過(guò)界面的用戶認(rèn)證,而通過(guò)selenium使用已保存的cookies信息直接登錄界面,下面是通過(guò)selenium在瀏覽器中添加cookies的代碼:
try {
File cooFile = new File(COOKIE_PATH);
if(!cooFile.exists()){
System.out.println("Not found the cookie file in path:" + COOKIE_PATH);
return;
}
BufferedReader bReader = new BufferedReader(new FileReader(cooFile));
String line;
while((line = bReader.readLine()) != null){
String arrCoo[] = line.split("/");
System.out.println(arrCoo.length);
String name="",value="",domain="",path="";
Date expiry = null;
boolean isSecure = false;
for (int i = 0; i < arrCoo.length; i++) {
name = arrCoo[0];
value = arrCoo[1];
domain = arrCoo[2];
path = arrCoo[3];
expiry = arrCoo[4] != "null"?new Date(arrCoo[4]):null;
isSecure = Boolean.parseBoolean(arrCoo[5]);
}
System.out.println(name +"/"+ value + "/" + domain + "/" + path + "/" + expiry + "/" + isSecure);
Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
driver.manage().addCookie(cookie);
}
} catch (Exception e) {
e.printStackTrace();
}

軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd