如何在Python WebDriver中为phantomjs/ghostdriver设置代理?

25 投票
5 回答
36070 浏览
提问于 2025-04-17 14:46

我正在尝试弄清楚如何通过HTTP代理来发送我的请求。

我这样初始化webdriver:

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

我查阅了文档和源代码,但似乎找不到如何在phantomjs中通过webdriver使用代理服务器的方法。

有什么建议吗?

5 个回答

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)
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

以下设置也很有用,特别是在使用可能加载很慢的代理时。

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)
74

下面是如何在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)

撰写回答