1

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
alexizydorczyk
  • 850
  • 1
  • 6
  • 25

1 Answers1

2

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' : [] })
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • hmm, this is probably on the right track but I'm getting an error - "undefined" is not a function at phantom.setProxy... – alexizydorczyk Aug 24 '15 at 22:34
  • I thought my Phantom version might be the problem but I'm running PhantomJS 1.9.8 - so I should be ok on that front – alexizydorczyk Aug 24 '15 at 22:42
  • `phantom.setProxy()` is available since PhantomJS 2. – Artjom B. Aug 24 '15 at 22:43
  • This is not thread-safe solution as it sets the proxy for the whole PhantomJS intance, not per webdriver session. Setting proxy with desired_capabilities would be much better... – gwaramadze Oct 25 '17 at 08:42
  • @gwaramadze If you have a better solution, there is always a possibility of posting another answer. – Artjom B. Oct 25 '17 at 17:22
  • I don't think it is possible now. As far as I read the code, the ghostdriver can be improved so that it accepts username and password. Currently these are always set to empty strings. But under the hood it is still calling setProxy. Ideally setProxy would also accept sessionId. Unfortunately I don't understand the way PhantomJS interacts with QT to start tweaking in this direction. But it must be somehow possible. Splash is also using QT and proxy can be set there on a per-request level. But well, Splash has other problems :) – gwaramadze Oct 25 '17 at 22:07