我要做的是将Cookie保存在文件中并重复使用该Cookie以避免每次登录,但我面临的错误是
[org.openqa.selenium.InvalidCookieDomainException:您只能为当前域设置Cookie]
下面我附上我的代码。 [阅读COOKIES的代码]
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='Email']")).sendKeys("<<USERNAME>");
driver.findElement(By.xpath("//input[@id='next']")).click();
driver.findElement(By.xpath("//input[@name='Passwd']")).sendKeys("<<PASSWORD>>");
driver.findElement(By.id("signIn")).click();
File file = new File("Cookies.data");
try
{
// Delete old file if exists
file.delete();
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
for(Cookie ck : driver.manage().getCookies())
{
Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
Bwrite.newLine();
System.out.println(ck.getExpiry());
}
Bwrite.flush();
Bwrite.close();
fileWrite.close();
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
[使用COOKIES的代码]
public static WebDriver driver;
public static void main(String[] args)
{
driver=new FirefoxDriver();
try{
File file = new File("Cookies.data");
FileReader fileReader = new FileReader(file);
BufferedReader Buffreader = new BufferedReader(fileReader);
String strline;
while((strline=Buffreader.readLine())!=null){
StringTokenizer token = new StringTokenizer(strline,";");
while(token.hasMoreTokens()){
String name = token.nextToken();
String value = token.nextToken();
String domain = token.nextToken();
String path = token.nextToken();
Date expiry = null;
String val;
if(!(val=token.nextToken()).equals("null"))
{
SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
expiry = df.parse(val);
}
Boolean isSecure = new Boolean(token.nextToken()).
booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
System.out.println(ck.getDomain());
System.out.println(ck);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
}
答案 0 :(得分:0)
在读取的cookie中,java类在驱动程序实例化之后立即包含一行(复制粘贴),以便像最后一样调用页面 - $.getJSON('/uploads/test.json', function (list) {
var newseries = {
name: '',
data: []
};
$.each(list, function (i, item) {
newseries.name = item.name;
newseries.data = item.data;
options.series.push(newseries);
});
var chart = new Highcharts.Chart(options);
这允许将cookie设置为来自同一域。