前几天爬某一网站,用到phantomjs,要加代理。千幸万苦找到这个方法,赶快记下。
方法一:
python目录下找到Lib\site-packages\selenium\webdriver\remote\remote_connection.py,
RemoteConnection里找到self._commands,
添加:
Command.EXECUTE_PHANTOM_SCRIPT:('POST', '/session/$sessionId/phantom/execute')。
不行的话,换成
"EXECUTE_PHANTOM_SCRIPT": ('POST', '/session/$sessionId/phantom/execute’)
添加之后
script = "phantom.setProxy('{ip}', {port})".format(ip=ip, port=port)
driver.execute('EXECUTE_PHANTOM_SCRIPT', {'script': script, 'args': []})。
方法二(最佳):
service_args = [
'--proxy=%s' % ip_html, # 代理 IP:prot (eg:192.168.0.28:808)
'--proxy-type=http’, # 代理类型:http/https
‘--load-images=no’, # 关闭图片加载(可选)
'--disk-cache=yes’, # 开启缓存(可选)
'--ignore-ssl-errors=true’ # 忽略https错误(可选)
]
driver = webdriver.PhantomJS(service_args=service_args)
:::想真正学到一种方法,除了百度谷歌,还要多看源码。