使用 Selenium webdriver 在 Firefox 中动态更改代理 [英] Dynamically changing proxy in Firefox with Selenium webdriver
问题描述
在使用 selenium webdriver 时,有没有办法动态更改 Firefox 使用的代理?
Is there any way to dynamically change the proxy being used by Firefox when using selenium webdriver?
目前我有使用代理配置文件的代理支持,但有没有办法在浏览器处于活动状态并运行时更改代理?
Currently I have proxy support using a proxy profile but is there a way to change the proxy when the browser is alive and running?
我当前的代码:
proxy = Proxy({
'proxyType': 'MANUAL',
'httpProxy': proxy_ip,
'ftpProxy': proxy_ip,
'sslProxy': proxy_ip,
'noProxy': '' # set this value as desired
})
browser = webdriver.Firefox(proxy=proxy)
提前致谢.
推荐答案
这是一个有点老的问题.但实际上可以通过hacky 方式"动态更改代理我将在 Firefox 中使用 Selenium JS,但您可以使用您想要的语言进行操作.
This is a slightly old question. But it is actually possible to change the proxies dynamically thru a "hacky way" I am going to use Selenium JS with Firefox but you can follow thru in the language you want.
第一步:访问about:config"
Step 1: Visiting "about:config"
driver.get("about:config");
第 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);
where use ${abcd} 是放置变量的地方,在上面的示例中,我使用 ES6 处理连接,如图所示,您可以使用其他连接方法,具体取决于您的选择语言.
Where use ${abcd} is where you put your variables, in the above example I am using ES6 which handles concatenation as shown, you can use other concatenation methods of your choice , depending on your language.
第 3 步::访问您的网站
driver.get("http://whatismyip.com");
说明:以上代码利用 Firefox 的 API 使用 JavaScript 代码更改首选项.
Explanation:the above code takes advantage of Firefox's API to change the preferences using JavaScript code.
这篇关于使用 Selenium webdriver 在 Firefox 中动态更改代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!