Python Selenium Webdriver - Changing proxy settings on the fly

前端 未结 2 1856
孤街浪徒
孤街浪徒 2020-12-05 15:39

I\'m currently successfully using the code below to use a proxy with the Selenium webdriver. Unfortunately, I can\'t seem to make it change the proxy settings without restar

2条回答
  •  悲哀的现实
    2020-12-05 16:20

    To set a proxy on the fly with Firefox:

    def set_proxy(driver, http_addr='', http_port=0, ssl_addr='', ssl_port=0, socks_addr='', socks_port=0):
    
        driver.execute("SET_CONTEXT", {"context": "chrome"})
    
        try:
            driver.execute_script("""
              Services.prefs.setIntPref('network.proxy.type', 1);
              Services.prefs.setCharPref("network.proxy.http", arguments[0]);
              Services.prefs.setIntPref("network.proxy.http_port", arguments[1]);
              Services.prefs.setCharPref("network.proxy.ssl", arguments[2]);
              Services.prefs.setIntPref("network.proxy.ssl_port", arguments[3]);
              Services.prefs.setCharPref('network.proxy.socks', arguments[4]);
              Services.prefs.setIntPref('network.proxy.socks_port', arguments[5]);
              """, http_addr, http_port, ssl_addr, ssl_port, socks_addr, socks_port)
    
        finally:
            driver.execute("SET_CONTEXT", {"context": "content"})
    

    Usage:

     driver = webdriver.Firefox()
    
     set_proxy(driver, http_addr="212.35.56.21", http_port=8080)
    
     driver.get("http://....")
    
     set_proxy(driver, http_addr="212.35.56.22", http_port=8888)
    
     driver.get("http://....")
    

提交回复
热议问题