使用Selenium webdriver在Firefox中动态更改代理

11

在使用Selenium Webdriver时,是否有办法动态更改Firefox使用的代理?

目前我已经使用代理配置文件实现了代理支持,但是当浏览器正在运行时,是否有一种方法可以更改代理?

我的当前代码:

proxy = Proxy({
    'proxyType': 'MANUAL',
    'httpProxy': proxy_ip,
    'ftpProxy': proxy_ip,
    'sslProxy': proxy_ip,
    'noProxy': '' # set this value as desired
    })
browser = webdriver.Firefox(proxy=proxy)

提前致谢。

4个回答

14

这是一个有点陈旧的问题。 但实际上可以通过一种“hacky方法”动态更改代理。 我将使用Selenium JS with Firefox,但您可以使用您想要的语言跟进。

步骤1:访问“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);

使用 ${abcd} 的地方是您放置变量的地方,在上面的示例中,我正在使用ES6处理连接,您可以根据您的语言选择其他连接方法。

第三步:访问您的网站

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

解释:以上代码利用Firefox的API使用JavaScript代码更改首选项。


2
也适用于Python。只需使用execute_script并将您的setupScript包装在"""引号中即可。 - jonincanada
@jonincanada,你能提供你的代码片段吗?谢谢。 - erotavlas

3
据我所知,只有两种方法可以更改代理设置,一种是通过配置文件(您正在使用的方式),另一种是在实例化驱动程序时使用驱动程序的功能(如此处所述)。不幸的是,这两种方法都无法满足您的需求,因为它们都发生在创建驱动程序之前。
我不得不问,为什么您想要更改代理设置?我唯一能够轻松想到的解决方案是将 Firefox 指向可以在运行时更改的代理。我不确定,但可能可以使用 browsermob-proxy 实现。

1

一种可能的解决方案是关闭webdriver实例,并通过在浏览器配置中传递新配置来创建它


0

试试selenium-wire,它甚至可以覆盖标头字段

from seleniumwire import webdriver 

options = {
    'proxy': {
          "http": "http://" + IP_PORT, 
          "https": "http://" + IP_PORT,
          'custom_authorization':AUTH
          },
    'connection_keep_alive': True,
    'connection_timeout': 30,
    'verify_ssl': False 
}

# Create a new instance of the Firefox driver
driver = webdriver.Firefox(seleniumwire_options=options)
driver.header_overrides = {
    'Proxy-Authorization': AUTH
}

# Go to the Google home page
driver.get("http://whatismyip.com")
driver.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接