我正在开发一个机器人。我希望机器人每 50 次搜索更改一次 webdriver 的代理。我有一个请求代理和套接字的 API,我存储了这些变量,到目前为止我一直在使用 firefox 配置文件来设置它,但效果不是很好。
考虑到我已经有了一个可行的代理和端口来源,你能告诉我有什么方法可以更改代理而不会使 webdriver 崩溃并在单个 session 中完成吗?
以前的尝试:
我试过这样设置 firefox 配置文件:
regions = {
'US': '', #USA is the default server
'Australia': #json response through the api,
'Canada': #json response through the api,
'France': #json response through the api,
'Germany': #json response through the api,
'UK': #json request response the api
}
for region in regions:
fp = webdriver.FirefoxProfile()
if(regions[region] != ''):
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.socks", regions[region])
fp.set_preference("network.proxy.socks_port", port)
这给我带来了一些问题,每次我想交换代理时我都必须开始一个新 session 。因此,我尝试通过 Firefox 选项(选项 - 常规 - 连接设置)更改代理,但结果是单击连接设置按钮后出现在屏幕上的弹出窗口无法通过 selenium 或 javascript(xul 文件)访问。
最佳答案
根据这个主题,这里是你的解决方案:
解决方案链接:Python Selenium Webdriver - Changing proxy settings on the fly
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);
关于python - 如何在单个 session 中多次更改我的 webdriver 上的代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609394/