
本文介绍如何在 Python 的 Selenium 中,通过 Chrome 新版无头模式(--headless=new)结合自定义代理认证扩展,实现稳定、可复用的代理访问方案。
本文介绍如何在 python 的 selenium 中,通过 chrome 新版无头模式(`--headless=new`)结合自定义代理认证扩展,实现稳定、可复用的代理访问方案。
Selenium 传统无头模式(--headless)不支持加载 Chrome 扩展,而代理认证(如 user:pass@host:port)在现代 Chrome 中无法直接通过 --proxy-server 参数传递(Chrome 自 71+ 版本起已移除对 --proxy-auth 的原生支持)。因此,唯一可靠方案是借助背景页注入认证逻辑的临时扩展 + 新版无头模式。
✅ 正确配置步骤
-
生成代理认证扩展(Manifest V3)
创建一个最小化 Chrome 扩展目录(例如 proxy_auth_ext/),包含以下文件:proxy_auth_ext/ ├── manifest.json └── background.js
manifest.json:
{ "manifest_version": 3, "name": "Proxy Auth Helper", "version": "1.0", "permissions": ["proxy", "storage", "tabs"], "host_permissions": ["<all_urls>"], "background": { "service_worker": "background.js" } }</all_urls>background.js(替换 YOUR_PROXY_HOST, YOUR_PROXY_PORT, YOUR_USERNAME, YOUR_PASSWORD):
const proxyConfig = { mode: "fixed_servers", rules: { singleProxy: { scheme: "http", host: "YOUR_PROXY_HOST", port: YOUR_PROXY_PORT }, bypassList: ["localhost"] } }; chrome.proxy.settings.set({value: proxyConfig, scope: "regular"}, () => {}); // 注入认证凭据(关键:需在首次请求前触发) chrome.webRequest.onAuthRequired.addListener( (details, callback) => { callback({ authCredentials: { username: "YOUR_USERNAME", password: "YOUR_PASSWORD" } }); }, {urls: ["<all_urls>"]}, ["blocking"] );</all_urls> -
启动 ChromeDriver 并加载扩展与新版无头模式
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--headless=new") # ✅ 必须使用此参数(非旧版 --headless) options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-gpu") options.add_argument("--disable-extensions-except=./proxy_auth_ext") # 扩展路径 options.add_argument("--load-extension=./proxy_auth_ext") driver = webdriver.Chrome(options=options) driver.get("https://httpbin.org/ip") print(driver.page_source) driver.quit()
⚠️ 注意事项
- 路径必须为绝对路径:--load-extension 接收的是绝对路径,建议使用 os.path.abspath("./proxy_auth_ext") 替代相对路径;
- Chrome 版本要求:需 Chrome 109+(对应 Chromium commit e9c5161);
- 避免混淆参数:--headless=new 与旧版 --headless 互斥,不可共存;若误用旧版,扩展将被静默忽略;
- 调试建议:开发阶段可先移除 --headless=new,以可视化方式确认扩展生效(地址栏右上角应出现扩展图标,且 chrome://extensions/ 中状态为启用);
- 替代方案局限性:requests 或 undetected-chromedriver 等库虽可绕过扩展,但无法保证所有网站(尤其含复杂 JS 渲染或反爬逻辑)下代理认证的稳定性。
✅ 总结
新版无头模式(--headless=new)是当前唯一支持代理认证扩展的官方方案。它保留了完整渲染引擎能力与扩展 API 兼容性,兼顾自动化需求与安全性。务必确保扩展结构合规、路径正确、Chrome 版本达标,并优先通过非无头模式验证逻辑后再切换至生产环境。











