初涉selenium+phantomjs

来源:互联网 发布:嵌入式linux开发前景 编辑:程序博客网 时间:2024/06/03 03:21

selenium github 地址

selenium api,这里可以看到源代码

可以参考这位大神的博客

这三个包提供了基础支持:
common,support,remote

其他几个是对各个浏览器驱动封装的调用接口:
chrome,firefox,phantomjs等

selenium.webdriver.remote.webdriver.WebDriver提供了driver的实现,chrome,firefox,phantomjs包下的driver都继承这个实现

接下来主要研究几个基础包和phantomjs:
driver.execute_script(“return navigator.userAgent”)获取当前浏览器
phantomjs的默认浏览器ua:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1

发生异常时停止加载当前页面:
IE浏览器用document.execCommand(“Stop”),
Chrome和Firefox用window.stop()
driver.execute_script(‘window.stop’)

driver.back(),driver.forward()可以向后向前跳转,是不是维护了一个通过新窗口获取的url的有序集合?

driver.add_cookie(dict):这个方法复制上一个请求的cookie,会出现一个错误:Can only set Cookies for the current domain
解决:
desc = webdriver.DesiredCapabilities.PHANTOMJS.copy()
desc[…]=…(其他设置)
cookies = driver.get_cookies()
driver.start_session(desc)
for cookie in cookies:
try:
driver.add_cookie(cookie)
except Exception as e:
print(repr(e)
这样处理后居然前后driver的cookie是一样的,达到复制cookie的目的,这让我没搞清楚它为什么会报错?!

一时理解,请不吝指正!