python - 实现 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()
,希望它会在程序不关闭的情况下更新?多线程会很好。
解决方案
您可以先尝试构造它,然后再将其传递给 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。如果您使用的是较低版本,则集中字符串也应该可以工作。
推荐阅读
- c - 为什么 5x5 矩阵上的内存地址用 4 分隔?
- python - Np.where 比较在浮点列中不起作用,该怎么做?
- node.js - 尝试使用 axios 为 spotify 做客户端授权流程
- python - sklearn 方法 model.fit(x---, y--)
- python - 我试图编写一个自动下载图像然后将它们发送到不同通道的机器人,但我遇到了错误
- javascript - 通过 JavaScript 客户端查找本地服务器的本地 IP
- reactjs - 放大配置文件:React Static App S3
- excel - 在 excel/vba 中更新文件路径
- c# - 在 C# 中的 WPF 应用程序中导出数据网格的子集
- c# - Xamarin Android WiFi 直接路由