Python Selenium Webdriver - 动态更改代理设置 [英] Python Selenium Webdriver - Changing proxy settings on the fly

查看:181
本文介绍了Python Selenium Webdriver - 动态更改代理设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前成功地使用下面的代码将代理与 Selenium webdriver 一起使用.不幸的是,我似乎无法在不重新启动整个浏览器的情况下更改代理设置.我曾希望简单地更新代理设置,就像我设置代理开始时所做的那样,会更改代理,但它似乎不起作用.对此问题的任何帮助将不胜感激.

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 restarting the whole browser. I had hoped that simply updating the proxy settings, just like I did to set the proxy to start with, would change the proxy, but it doesn't seem to work. Any help on this subject would be greatly appreciated.

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)

推荐答案

这是一个有点老的问题.但实际上可以通过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.

第 1 步:访问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 处理连接,如图所示,您可以使用其他连接方法,具体取决于您的选择语言.(SetupScript 是一个字符串,其中包含要运行的脚本,用``)

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.(The SetupScript is a string containing the script to be runned enclosed by ``)

第 3 步::访问您的网站

driver.get("https://whatismyip.com");

说明:以上代码利用 Firefox 的 API 使用 JavaScript 代码更改首选项.

Explanation:the above code takes advantage of Firefox's API to change the preferences using JavaScript code.

这篇关于Python Selenium Webdriver - 动态更改代理设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆