3

I am aware that I can set proxy settings for phantomjs on initialization using service_args but restarting phantomjs every time just to change proxy setting seems wasteful. In javascript changing proxy at runtime would be done with setProxy function. How can I make this work in Python using selenium?

John
  • 153
  • 1
  • 4
  • possible duplicate of [How to run webpage code with PhantomJS via GhostDriver (selenium)](http://stackoverflow.com/questions/23125557/how-to-run-webpage-code-with-phantomjs-via-ghostdriver-selenium) – Artjom B. Jun 05 '15 at 11:12
  • have you tried the execute_script function to execute javascript ? http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script – HaseebR7 Jun 05 '15 at 11:13
  • @HaseebR7 Thanks, that's exactly what I was looking for. Just, I have no experience in Javascript so if it's not asking too much would you care to show example usage, preferably using setProxy(). – John Jun 05 '15 at 11:18
  • `execute_script()` does not what you want, because it executes the given script on the page. You cannot set the proxy with it. – Artjom B. Jun 05 '15 at 12:05

1 Answers1

3

Trying various options and reading a bit of code, I realized that it is possible to dynamically change proxies in python + selenium + phantomjs. For posterity here is a sample code:

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

Happy ghosting ;)

Abhimanu Kumar
  • 1,751
  • 18
  • 20