Search code examples
javascriptpython-3.xseleniumsplinter

Changing Proxy Settings without Closing the Driver in Selenium/Splinter


In an older version of Splinter/Selenium this was said not to be possible. This answer a few years later claims it is possible with JavaScript, but this code doens't work for me (I might have just failed to translate it to Python). This answer closes the browser and then re-opens it, and I need the window/browser to stay open.

With plugins like FoxyProxy, its very easy to change the proxy on-the-fly, but I don't think Selenium can interact with plugins because they are page elements?

As Splinter is designed to be a less verbose wrapper for Selenium, it would be awesome if there was an easy way to accomplish this. That being said, any hack to just have this functionality would be appreciated.


Solution

  • You need to use it like below

    browser.visit("about:config")
    
    script = """
    var prefs = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefBranch);
    
    prefs.setIntPref("network.proxy.type", 1);
    prefs.setCharPref("network.proxy.http", "{0}");
    prefs.setIntPref("network.proxy.http_port", "{1}");
    prefs.setCharPref("network.proxy.ssl", "{0}");
    prefs.setIntPref("network.proxy.ssl_port", "{1}");
    prefs.setCharPref("network.proxy.ftp", "{0}");
    prefs.setIntPref("network.proxy.ftp_port", "{1}");
    """
    
    browser.execute_script(script.format("ProxyIP", "PORT"))
    

    PS: Credits to Python Selenium Webdriver - Changing proxy settings on the fly