PhantomJS Proxy when using Remote Webdriver?

2019-05-29 21:47发布

问题:

I am trying to use selenium in python with PhantomJS. I am running a selenium hub server so am using webdriver.Remote to start a webdriver.

The normal way to pass a proxy to PhantomJS is:

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

This won't workthough for

webdriver.Remote(service_args=service_args)

As webdriver.Remote takes only desired_capabilities, not service args, as a parameter.

Is there any way to pass a proxy to PhantomJS as a desired_capibility?

The typical way one would do so with a Firefox webdriver does not work.

回答1:

Since the PhantomJS instance already runs, it wouldn't make sense to pass commandline options to the RemoteDriver constructor. There is a way though.

PhantomJS itself supports a programmatic way to configure a proxy through phantom.setProxy(ip, port, type, un, pw) (not documented, but available since PhantomJS 2). This has to be executed in the phantom context, so driver.execute_script() won't work here.

GhostDriver accepts such script that are to be executed in the phantom context through a special command which you can invoke like this (source):

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