Selenium启动Chrome非预期实例:如何调用系统默认Chrome?
解决方案:让Selenium调用系统默认Chrome实例
核心问题分析
- 配置文件路径错误:你之前把
--user-data-dir指向了Default子文件夹,而Chrome要求这个参数指向包含所有用户配置的User Data目录,Default只是其中一个用户配置文件夹——这导致Chrome加载了新的临时配置,而非系统默认配置,所以没有浏览历史。 - Selenium默认参数干扰:Selenium启动Chrome时会自动添加大量自动化相关参数,这些参数会让Chrome行为和手动启动不一致,甚至触发验证码。
具体修复步骤
1. 修正配置文件路径
将user_data改为Chrome的User Data目录,再通过--profile-directory=Default指定加载默认用户配置:
user_data = r'C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data'
然后添加对应参数:
options.add_argument(f'--user-data-dir={user_data}') options.add_argument('--profile-directory=Default') # 指定加载默认配置文件
2. 优化ChromeOptions,模拟手动启动
添加参数移除自动化特征,让Chrome行为更接近手动启动:
options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("--no-first-run") options.add_argument("--no-service-autorun") options.add_argument("--password-store=basic") options.add_argument("--start-maximized") # 模拟手动启动的窗口状态 options.add_experimental_option("excludeSwitches", ["enable-automation", "enable-logging"]) options.add_experimental_option('useAutomationExtension', False)
3. Selenium 4 驱动初始化(替代executable_path)
Selenium 4推荐使用ChromeService配合ChromeDriverManager自动管理驱动,无需手动指定路径。先安装依赖:
pip install webdriver-manager
然后在代码中初始化驱动:
from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
完整修复后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager user_data = r'C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data' options = webdriver.ChromeOptions() options.binary_location = r'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' # 配置文件相关参数 options.add_argument(f'--user-data-dir={user_data}') options.add_argument('--profile-directory=Default') # 模拟手动启动的参数 options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("--no-first-run") options.add_argument("--no-service-autorun") options.add_argument("--password-store=basic") options.add_argument("--start-maximized") options.add_argument('disable-infobars') # 移除自动化标识 options.add_experimental_option("excludeSwitches", ["enable-automation", "enable-logging"]) options.add_experimental_option('useAutomationExtension', False) # Selenium 4 驱动初始化 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) driver.get('https://www.google.com/ncr') search_box = driver.find_element(By.NAME, 'q') search_box.send_keys('how are you') search_box.send_keys(Keys.RETURN) sleep(1200) driver.quit()
验证要点
- 启动后访问
chrome://version,确认Profile Path是系统默认配置路径,且启动参数和手动启动的差异大幅减少。 - 此时Chrome会加载你的浏览历史、书签等默认数据,访问Google搜索也不会触发验证码。
内容的提问来源于stack exchange,提问作者Rogers
相关产品推荐
相关产品推荐

