Selenium WebDriver处理cookie

发表于:2014-10-09 10:53

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:to be crazy    来源:51Testing软件测试网采编

  这里,我简单封装了chrome webdriver
import java.util.Arrays;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class DriverFactory {
public static WebDriver create() {
// TODO Auto-generated method stub
String chromdriver="E:\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromdriver);
ChromeOptions options = new ChromeOptions();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches",
Arrays.asList("--start-maximized"));
options.addArguments("--test-type", "--start-maximized");
WebDriver driver=new ChromeDriver(options);
return driver;
}
}
   接下来 ,读取browser.data,生成cookie  把cookie加载到浏览器
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
public class UseCookieLogin {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver=DriverFactory.create();
driver.get("http://selenium.jd-app.com/wp-admin/");
try
{
File file=new File("broswer.data");
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!= null)
{
StringTokenizer str=new StringTokenizer(line,";");
while(str.hasMoreTokens())
{
String name=str.nextToken();
String value=str.nextToken();
String domain=str.nextToken();
String path=str.nextToken();
Date expiry=null;
String dt;
if(!(dt=str.nextToken()).equals(null))
{
//expiry=new Date(dt);
System.out.println();
}
boolean isSecure=new Boolean(str.nextToken()).booleanValue();
Cookie ck=new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
driver.get("http://selenium.jd-app.com/wp-admin/");
}
}
  管理页面只有登陆后才能打开,如果未登录就会跳转登陆页面,当我们加载cookie后,看到的是登陆后的页面
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号