分享 Python+Webdriver+Phantomjs,设置自定义 headers 的方法

2016-11-06 18:55:45 +08:00
 imcocc

发现以前修改 Phantomjs 的头部代码都不能用,辛苦找的,记录一下帮助更多人(注意 python 缩进)

2016 年 11 月 6 号测试有效(python 2.7 Phantomjs 2.11)

这是一个代码区块。

from selenium import webdriver

from selenium.webdriver import DesiredCapabilities

driver=webdriver.PhantomJS(executable_path='存放路径\phantomjs.exe')

desired_capabilities= DesiredCapabilities.PHANTOMJS.copy()

headers = {'Accept': '*/*',

'Accept-Language': 'en-US,en;q=0.8',

'Cache-Control': 'max-age=0',

'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',#这种修改 UA 也有效

'Connection': 'keep-alive'

'Referer':'http://www.baidu.com/'

}

for key, value in headers.iteritems():

    desired_capabilities['phantomjs.page.customHeaders.{}'.format(key)] = value

desired_capabilities['phantomjs.page.customHeaders.User-Agent'] ='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'

driver= webdriver.PhantomJS(desired_capabilities=desired_capabilities)

driver.get("http://www.myip.cn/judge.php")

print driver.page_source

参考: https://gist.github.com/ozen/e24c4d40b53a774d9b36

14901 次点击
所在节点    Python
7 条回复
terence4444
2017-02-07 23:39:54 +08:00
调 2 次 webdriver.PhantomJS 是不是有点不太对?
driver=webdriver.PhantomJS(executable_path='存放路径\phantomjs.exe', desired_capabilities=desired_capabilities)
怎么样?
imcocc
2017-02-08 12:57:26 +08:00
@terence4444
忘了当时怎么想的了,当时没报错。我也觉得可以缩写成你写的, 你测试一下可用不
terence4444
2017-02-08 15:10:42 +08:00
@imcocc 好的 回头我试一下再来
terence4444
2017-02-08 22:47:54 +08:00
@imcocc 试了一下你的代码会报错,又试了一下我的,虽然没报错但看不出来有没有用。目前没有指定 header 的页面,现在正在搞别的东西,等有空了搞一下试试,感谢分享。
imcocc
2017-02-09 01:23:54 +08:00
@terence44
访问 http://www.myip.cn/judge.php 查看 headers 的值。
搜索了一下,如你所说 。
第三行
driver=webdriver.PhantomJS(executable_path='存放路径\phantomjs.exe')
删除

倒数第三行修改为
driver=webdriver.PhantomJS(executable_path='存放路径\phantomjs.exe', desired_capabilities=desired_capabilities)
tanywei
2017-03-17 17:27:38 +08:00
remote 的用不了吧?
imcocc
2017-03-17 18:51:50 +08:00
@tanywei remote 的没用过 你看着改改试试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/318511

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX