Skip to main content
 首页 » 编程设计

python之如何动态更改 chrome 驱动程序中的代理

2024年11月24日42birdshome

我在更改代理时遇到问题,每次我加载新页面时,它都会创建另一个浏览器进程。我找到了适用于 Firefox 的解决方案,但没有找到适用于 Chrome 浏览器的解决方案。

self.options = webdriver.ChromeOptions() 
self.options.add_argument("--start-maximized") 
self.options.add_argument("--disable-popup-blocking") 
self.options.add_argument('--proxy-server=%s' % 'proxy') 

Firefox 解决方案:Python Selenium Webdriver - Changing proxy settings on the fly

请您参考如下方法:

我在Java/Scala中找到了一个解决方案,我发现ChromeOptions extends to MutableCapabilities,顾名思义,是可变的,所以我在scala中得到了以下代码,Java需要稍微改变一下

val proxy = new org.openqa.selenium.Proxy() 
val proxyStr = "127.0.0.1:1080" 
proxy.setHttpProxy(proxyStr) 
val option = new ChromeOptions() 
option.setProxy(proxy) 
chromeDriver.getCapabilities.merge(option) // will change proxy used by the driver