如何为undetected-chromedriver配置带身份验证的代理?
问题
需要使用undetected-chromedriver访问网站,同时添加带身份验证的代理,但常规chromedriver的方法无效,已尝试以下两种方式:
- 结合seleniumwire的尝试:
from seleniumwire import webdriver import undetected_chromedriver as uc options = webdriver.ChromeOptions() seleniumwire_options = {'proxy': {'https': 'type://username:pass@host:port'}} driver = uc.Chrome(use_subprocess=True, seleniumwire_options=seleniumwire_options)
- 直接添加代理参数的尝试:
import undetected_chromedriver as uc options = uc.ChromeOptions options.add_argument("--proxy-server=https://username:pass@host:port") driver = uc.Chrome(use_subprocess=True, options=options)
求适用于undetected-chromedriver的有效代理配置方法。
有效解决方案
方法1:通过Chrome扩展注入代理认证
直接在--proxy-server中携带用户名密码易被拦截,可通过自定义Chrome扩展自动完成代理认证:
创建两个扩展文件:
manifest.json:
{ "version": "1.0.0", "manifest_version": 3, "name": "Proxy Auth Extension", "permissions": ["proxy", "tabs", "storage", "activeTab", "scripting"], "host_permissions": ["<all_urls>"], "background": { "service_worker": "background.js" }, "minimum_chrome_version": "100" }background.js:
chrome.proxy.settings.set({value: { mode: "fixed_servers", rules: { singleProxy: { scheme: "https", host: "你的代理host", port: 你的代理端口 }, bypassList: ["localhost"] } }, scope: "regular"}, function() {}); chrome.webRequest.onAuthRequired.addListener( function(details) { return { authCredentials: { username: "你的用户名", password: "你的密码" } }; }, {urls: ["<all_urls>"]}, ['blocking'] );将文件打包为zip(或直接用文件夹路径),在undetected-chromedriver中加载:
import undetected_chromedriver as uc options = uc.ChromeOptions() # 替换为你的扩展文件路径 options.add_extension("proxy_auth_extension.zip") driver = uc.Chrome(use_subprocess=True, options=options) driver.get("https://www.example.com")
方法2:修正SeleniumWire与undetected-chromedriver的结合方式
调整初始化逻辑,正确关联两者:
import undetected_chromedriver as uc from seleniumwire import webdriver options = uc.ChromeOptions() driver = webdriver.Chrome( options=options, seleniumwire_options={ 'proxy': { 'http': 'http://username:password@host:port', 'https': 'https://username:password@host:port', 'no_proxy': 'localhost,127.0.0.1' } }, driver_executable_path=uc.install() ) driver.get("https://www.example.com")
方法3:通过Chrome偏好设置配置代理
利用experimental_options注入代理认证信息:
import undetected_chromedriver as uc options = uc.ChromeOptions() proxy_host = "你的代理host" proxy_port = "你的代理端口" proxy_username = "你的用户名" proxy_password = "你的密码" options.add_argument(f'--proxy-server=http://{proxy_host}:{proxy_port}') options.add_experimental_option( "prefs", { "credentials_enable_service": False, "profile.password_manager_enabled": False, "proxy": { "mode": "fixed_servers", "server": f"{proxy_host}:{proxy_port}", "username": proxy_username, "password": proxy_password } } ) driver = uc.Chrome(use_subprocess=True, options=options) driver.get("https://www.example.com")
内容的提问来源于stack exchange,提问作者Katerina_GG
相关产品推荐
相关产品推荐

