tob*_*oef 9 python proxy selenium webdriver python-3.x
我目前正在成功使用下面的代码来使用Selenium webdriver的代理.不幸的是,我似乎无法在不重新启动整个浏览器的情况下更改代理设置.我曾希望简单地更新代理设置,就像我设置代理开始一样,会改变代理,但它似乎不起作用.对此主题的任何帮助将不胜感激.
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", proxyAddress)
profile.set_preference("network.proxy.http_port", proxyPort)
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
Run Code Online (Sandbox Code Playgroud)
这是一个有点老的问题。但是实际上可以通过“ hacky way ” 动态更改代理,我将在Firefox中使用Selenium JS,但是您可以使用所需的语言。
第1步:访问“ about:config”
driver.get("about:config");
Run Code Online (Sandbox Code Playgroud)
步骤2:运行更改代理的脚本
var setupScript=`var prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
prefs.setIntPref("network.proxy.type", 1);
prefs.setCharPref("network.proxy.http", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.http_port", "${proxyUsed.port}");
prefs.setCharPref("network.proxy.ssl", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.ssl_port", "${proxyUsed.port}");
prefs.setCharPref("network.proxy.ftp", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.ftp_port", "${proxyUsed.port}");
`;
//running script below
driver.executeScript(setupScript);
//sleep for 1 sec
driver.sleep(1000);
Run Code Online (Sandbox Code Playgroud)
在哪里使用$ {abcd}放置变量,在上面的示例中,我使用的是ES6,它处理如图所示的串联,您可以根据自己的语言使用其他选择的串联方法。(SetupScript是一个字符串,包含要运行的脚本包含在``)中
步骤3:访问您的网站
driver.get("https://whatismyip.com");
Run Code Online (Sandbox Code Playgroud)
说明:以上代码利用Firefox的API来使用JavaScript代码更改首选项。
使用 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"})
Run Code Online (Sandbox Code Playgroud)
用法:
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://....")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2927 次 |
| 最近记录: |