如何在python webdriver中为phantomjs/ghostdriver设置代理?

eri*_*kcw 24 python proxy webdriver phantomjs ghostdriver

我试图弄清楚如何通过HTTP代理路由我的请求.

我正在初始化这样的webdriver:

user_agent = 'my user agent 1.0'
DesiredCapabilities.PHANTOMJS['phantomjs.page.settings.userAgent'] = user_agent
driver = webdriver.PhantomJS()
Run Code Online (Sandbox Code Playgroud)

我已经浏览了文档和源代码,似乎无法通过webdriver找到使用phantomjs代理服务器的方法.

有什么建议?

Ale*_*Nik 72

下面是如何在Python中为PhantomJs设置代理的示例.您可以更改代理类型:socks5/http.

service_args = [
    '--proxy=127.0.0.1:9999',
    '--proxy-type=socks5',
    ]
browser = webdriver.PhantomJS('../path_to/phantomjs',service_args=service_args)
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用需要身份验证的代理,则需要在`service_args`列表'' - proxy-auth = username:password'`中添加另一个字段. (12认同)

Pyk*_*ler 6

我挖了一点,我发现功能在那里,但它没有暴露.所以它需要一个方便的猴子扳手来修补它.以下是适用于我的解决方案,直到此功能在webdriver调用中完全公开.

编辑:似乎service_args现在暴露,你不再需要猴子补丁selenium使用代理...请参阅@ alex-czech答案如何使用.

from selenium import webdriver
from selenium.webdriver.phantomjs.service import Service as PhantomJSService

phantomjs_path = '/usr/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs'
# monkey patch Service temporarily to include desired args
class NewService(PhantomJSService):
    def __init__(self, *args, **kwargs):
        service_args = kwargs.setdefault('service_args', [])
        service_args += [
            '--proxy=localhost:8080',
            '--proxy-type=http',
        ]
        super(NewService, self).__init__(*args, **kwargs)
webdriver.phantomjs.webdriver.Service = NewService
# init the webdriver
self.driver = webdriver.PhantomJS(phantomjs_path)
# undo monkey patch
webdriver.phantomjs.webdriver.Service = PhantomJSService
Run Code Online (Sandbox Code Playgroud)

以下设置也很有用,尤其是在使用可能需要很长时间才能加载的代理时.

max_wait = 60
self.driver.set_window_size(1024, 768)
self.driver.set_page_load_timeout(max_wait)
self.driver.set_script_timeout(max_wait)
Run Code Online (Sandbox Code Playgroud)


Chi*_*edo 5

以下是如何使用Ruby中的Webdriver执行相同的操作.在我挖掘源代码之前,我无法在网上找到它:

phantomjs_args = [ '--proxy=127.0.0.1:9999', '--proxy-type=socks5']
phantomjs_caps = { "phantomjs.cli.args" => phantomjs_args }
driver = Selenium::WebDriver.for(:phantomjs, :desired_capabilities => phantomjs_caps)
Run Code Online (Sandbox Code Playgroud)