使用undetected-chromedriver配置代理后无法访问网站的问题
我尝试通过配置代理的undetected-chromedriver访问网站,使用的代码如下:
from time import sleep import json import undetected_chromedriver as webdriver from selenium.webdriver.chromium.service import ChromiumService from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options service = ChromiumService(executable_path=ChromeDriverManager().install()) config = json.load(open('config.json','r')) def checker(proxy): opts = Options() opts.binary_location = config['chrome-path'] opts.add_argument("--proxy-server=" + "\"" + proxy + "\"") driver = webdriver.Chrome(version_main=110, options=opts, service=service) sleep(5) driver.get('https://whatismyip.com') sleep(100) checker('IP:PORT')
config.json内容:
{ "chrome-path": "/bin/ungoogled-chromium" }
结果浏览器无法访问任何网站,但通过命令行执行ungoogled-chromium --proxy-server="IP:PORT"(使用相同代理IP)启动浏览器时,所有网站均可正常加载。尝试seleniumwire也无效,希望找到原因及解决办法。
可能的原因及解决办法
1. 代理参数的多余引号导致配置错误
命令行中的引号是Shell用来防止参数被拆分的,但通过ChromeOptions传递参数时,不需要添加额外引号。你的代码中给代理地址加了双引号,会导致Chrome识别的代理地址变成"IP:PORT"(包含引号),这显然是无效的。
解决办法:移除代理参数中的引号,修改为:
opts.add_argument(f"--proxy-server={proxy}") # 或者用字符串拼接:opts.add_argument("--proxy-server=" + proxy)
2. Driver版本与浏览器版本不匹配
你指定了version_main=110,但实际使用的ungoogled-chromium版本可能不是110,版本不匹配会导致浏览器与driver通信异常,进而影响代理配置生效。
解决办法:
- 先查看浏览器版本:执行命令
ungoogled-chromium --version,获取主版本号 - 将代码中的
version_main修改为对应版本号,或者直接移除该参数,让undetected-chromedriver自动匹配版本:
driver = webdriver.Chrome(options=opts, service=service)
3. ChromiumService与undetected-chromedriver的兼容性问题
undetected-chromedriver本身已经内置了driver管理逻辑,手动指定ChromiumService可能会产生冲突,导致代理配置无法正确传递。
解决办法:尝试移除service参数,让undetected-chromedriver自行处理driver:
driver = webdriver.Chrome(version_main=xxx, options=opts)
4. 代理需要认证(若适用)
如果你的代理需要账号密码认证,仅通过--proxy-server参数无法完成配置,命令行能正常访问可能是因为浏览器已经保存了认证信息。
解决办法:可以使用seleniumwire来处理带认证的代理:
from seleniumwire import webdriver as wire_driver opts = Options() opts.binary_location = config['chrome-path'] driver = wire_driver.Chrome(options=opts) driver.proxy = { 'http': f'http://username:password@{proxy}', 'https': f'https://username:password@{proxy}', 'no_proxy': 'localhost,127.0.0.1' }
修改后的完整示例代码
from time import sleep import json import undetected_chromedriver as webdriver from selenium.webdriver.chrome.options import Options config = json.load(open('config.json','r')) def checker(proxy): opts = Options() opts.binary_location = config['chrome-path'] # 移除多余引号,正确传递代理参数 opts.add_argument(f"--proxy-server={proxy}") # 让undetected-chromedriver自动匹配浏览器版本,无需手动指定service driver = webdriver.Chrome(options=opts) sleep(5) driver.get('https://whatismyip.com') sleep(100) checker('IP:PORT')
内容的提问来源于stack exchange,提问作者elainaStackOverFlow

