使用远程Webdriver时PhantomJS代理?

时间:2015-08-24 21:42:09

标签: python selenium-webdriver phantomjs ghostdriver remotewebdriver

我正在尝试使用PhantomJS在python中使用selenium。我正在运行selenium hub服务器,所以我使用webdriver.Remote来启动webdriver。

将代理传递给PhantomJS的常规方法是:

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

这不会为

工作
webdriver.Remote(service_args=service_args)

as webdriver.Remote只接受desired_capabilities,而不是service args作为参数。

有没有办法将代理传递给PhantomJS作为desired_capibility?

使用Firefox webdriver执行此操作的典型方法无效。

1 个答案:

答案 0 :(得分:2)

由于PhantomJS实例已经运行,因此将命令行选项传递给RemoteDriver构造函数是没有意义的。虽然有一种方法。

PhantomJS本身支持通过phantom.setProxy(ip, port, type, un, pw)配置代理的编程方式(未记录,但可从PhantomJS 2开始提供)。这必须在幻像环境中执行,因此driver.execute_script()不会在这里工作。

GhostDriver接受这样的脚本,这些脚本将通过一个特殊的命令在幻像上下文中执行,你可以这样调用它(source):

driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.execute('executePhantomScript', {'script': '''phantom.setProxy("10.0.0.1", 12345);''', 'args' : [] })