【WebDriver】firefox读写cookie的问题

来源:互联网 发布:如何评价蒋方舟 知乎 编辑:程序博客网 时间:2024/04/30 11:56
【测试内容】

1.打开一个设定画面,进行一些设定。
2.关闭浏览器
3.再次打开该设定画面,确认画面上的内容与之前设定的一致。

【问题描述】

    IE测试没有任何问题,只是在firefox中遇到了下面的问题:
    当做好设定,关闭浏览器,再次通过webdriver打开设定画面时,又变成了未设定之前的样子。也就是之前的设定(存放在cookie中)并没有被浏览器读到。

    下面的代码是网上查阅到的,据说是可以每次启动浏览器的时候启用cookie功能。实现代码是ruby。刚开始我的理解是,下面的操作,可以使得webdriver的测试,自动地去读取浏览器的cookie文件。
Ruby code
?
1
2
Watir::Browser.new(:firefox, {:profile => 'default'}) # watir webdriver
Selenium::WebDriver.for(:firefox:profile => 'default'#selenium 2
 

    于是我自己查了一下api,想在java代码中用了类似的方法,看看能否解决这个问题。结果也失败了。
Java code
?
1
2
3
FirefoxProfile profile = new FirefoxProfile();(new一个profile,代表使用默认值)
WebDriver driver = new FirefoxDriver(profile);
driver.get(url);


后来看到stackoverflow上面一些大神的留言才知道,其实上面的ruby代码中,所谓的启用cookie,也只是该单个instance独自的cookie,与浏览器是无关的。也就是说,上面的java代码并没有错误,它只是声明该instance的cookie功能可以使用,当然如果你什么都不设定,一般来说它也是有效地。

 Each of instances has own profile with cookies. If you're runing few drivers in parallel, you may need to

 clear cookies for each of them. 

Selenium doesn't store the cookies, the browser does. So the answer to "where [the browser] stores 

the cookies" will be different for each browser. But since Selenium always starts the browser with a 

clean profile, you shouldn't have to do this - there are no cookies when the browser starts.


在firefox中,每一个webdriver实例,都有其独自的cookie信息存储文件。画面操作如果有读取cookie的操作,那么默认的是读取的当前这个instance的独自的cookie文件,而不是浏览器的cookie文件。这是一个容易引起误会的地方。

在了解了原理之后,解决问题就变的简单了!只要保证在测试的过程中,当前的这个driver instance一直存在,那么之前保存的cookie信息也就能再次被正确的读取到了。
原创粉丝点击