首页 > 解决方案 > 实现 Selenium 以使用更改的身份验证代理

问题描述

我正在尝试让 selenium 使用会在某个时间点发生变化的代理。

from seleniumwire import webdriver
def proxyManage():
    proxyChange("test.com", "8000", "user1", "password1")

def proxyChange(host, port, username, password):
    options = {
        'proxy': {
            'http': 'http://'+username+':'+password+'@'+host+':'+port, 
            'https': 'https://'+username+':'+password+'@'+host+':'+port,
        }
    }
    PATH = "D:/Programming/undetectable chrome/chromedriver.exe"
    browser = webdriver.Chrome(PATH, options=options)
    browser.get("https://whatismyipaddress.com/")
    

proxyManage()

所以我导入 seleniumwire 因为我不确定 selenium 如何正常使用代理。现在,当我尝试运行该程序以在网站上测试它是否有效时,我收到以下错误,

Traceback (most recent call last):
  File "D:\Programming\Python\proxyTest.py", line 20, in <module>
    proxyManage()
  File "D:\Programming\Python\proxyTest.py", line 6, in proxyManage
    proxyChange("test.com", "8000", "user1", "password1")
  File "D:\Programming\Python\proxyTest.py", line 16, in proxyChange
    browser = webdriver.Chrome(PATH, options=options)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\seleniumwire\webdriver\browser.py", line 97, in __init__
    chrome_options.add_argument('proxy-bypass-list=<-loopback>')
AttributeError: 'dict' object has no attribute 'add_argument'

因此,首先有一种方法可以将这些参数传递给proxyChange()而不会出错。这个想法是有一个计数器proxyManage(),每次运行时它都会移动proxy.txt文件中的下一行,然后解析这些参数proxyChange(),希望它会在程序不关闭的情况下更新?多线程会很好。

标签: pythonpython-3.xseleniumselenium-webdriverselenium-chromedriver

解决方案


您可以先尝试构造它,然后再将其传递给 dict:

http_proxy = f"'http://{username}:{password}@{host}:{port}"
https_proxy = f"'https://{username}:{password}@{host}:{port}"
options = {
        'proxy': {
            'http': http_proxy,
            'https': https_proxy
        }
    }

这仅适用于 Python >=3.6。如果您使用的是较低版本,则集中字符串也应该可以工作。


推荐阅读