如何在单个会话中多次更改我的webdriver上的代理?

问题描述 投票:8回答:2

我正在研究机器人。我希望机器人每50次搜索更改webdriver的代理。我有一个请求代理和套接字的API,我存储这些变量,到目前为止我一直在使用firefox配置文件进行设置,但这并不能很好地工作。

因此,鉴于我已经有了一个可行的代理和端口来源,你能告诉我任何方式我可以更改代理而不会崩溃webdriver并在单个会话上执行吗?

以前的尝试:

我尝试以这种方式设置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)

这给我带来了一些问题,每次我想交换代理时我都要开始新的会话。所以我试图通过Firefox选项(选项 - 一般 - 连接设置)更改代理,但结果是单击连接设置按钮后无法通过selenium或javascript(xul文件)访问屏幕上显示的弹出窗口。

python selenium firefox proxy
2个回答
4
投票

根据这个主题,这是你的解决方案:

解决方案链接: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);

5
投票

我能够通过在aboutLconfig上通过JS设置首选项然后在selenium中使用execute_script来通过python部署js来解决这个问题:

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:
        driver.get("about:config")
        time.sleep(3)
        driver.find_element_by_css_selector("window#config deck#configDeck vbox#warningScreen vbox#warningBox.container vbox.description hbox.button-container button#warningButton.primary").click()
        time.sleep(3)
        driver.execute_script('var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); prefs.setIntPref("network.proxy.type", 1); prefs.setCharPref("network.proxy.socks", "' + regions[region] + '"); prefs.setIntPref("network.proxy.socks_port", 9998);')
        time.sleep(3)
        driver.get('https://www.whatsmyip.com/')
        time.sleep(10)

随着脚本的执行我将分别用regionport更改socks主机和socks主机的服务值。

它基本上与通过selenium设置配置文件相同,但这样您就可以在机器人运行时执行此操作。您也可以通过这种方式更改用户代理和几乎任何您喜欢的内容。

© www.soinside.com 2019 - 2024. All rights reserved.