使用Python Selenium+ChromeDriver时出现Chrome for Testing异常问题
解决Chrome for Testing自动启动及采集器异常问题
1. 强制指定本地常规Chrome路径
初始化WebDriver时,明确指定你日常使用的Chrome浏览器可执行文件路径,避免Selenium自动切换到Chrome for Testing:
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() # 替换为你本地Chrome的实际路径 # Windows示例 options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe" # macOS示例:/Applications/Google Chrome.app/Contents/MacOS/Google Chrome # Linux示例:/usr/bin/google-chrome driver = webdriver.Chrome(options=options)
2. 禁用Selenium自动驱动/浏览器管理
Selenium 4.6+版本默认启用自动管理机制,会自动下载Chrome for Testing和对应驱动。可以通过两种方式禁用:
方式1:设置环境变量
- Windows命令行:
set SELENIUM_MANAGER_SKIP=true - macOS/Linux终端:
export SELENIUM_MANAGER_SKIP=true
方式2:代码中指定本地驱动
from selenium import webdriver from selenium.webdriver.chrome.service import Service # 指定你本地旧版ChromeDriver的路径 service = Service(executable_path=r"C:\your\chromedriver\path\chromedriver.exe") options = webdriver.ChromeOptions() # 同时指定常规Chrome路径 options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe" driver = webdriver.Chrome(service=service, options=options)
3. 优化浏览器配置,提升稳定性与速度
添加以下选项,移除自动化提示并减少资源占用:
options.add_argument("--disable-infobars") # 关闭"Chrome由自动化测试软件控制"提示 options.add_argument("--disable-extensions") # 禁用扩展,降低资源消耗 options.add_argument("--disable-gpu") # 禁用GPU加速,避免环境兼容问题 options.add_argument("--no-sandbox") # 禁用沙箱模式,提升启动速度 options.add_experimental_option("useAutomationExtension", False) options.add_experimental_option("excludeSwitches", ["enable-automation"])
4. 验证Chrome与ChromeDriver版本兼容性
即使你认为版本未变动,也需要确认两者主版本号完全一致(比如Chrome是125.x,ChromeDriver也必须是125.x):
- 查看Chrome版本:在地址栏输入
chrome://version/ - 查看ChromeDriver版本:命令行执行
chromedriver --version
如果版本不匹配,手动下载对应版本的ChromeDriver替换旧文件。
内容的提问来源于stack exchange,提问作者Axel Hippolite
相关产品推荐
相关产品推荐

