Selenium调用Chrome配置文件触发WebDriverException错误求助
问题背景
使用Selenium启动带有指定Chrome配置文件时,触发WebDriverException,提示Chrome启动失败、DevToolsActivePort文件不存在、Chrome已崩溃。移除配置文件参数后程序正常运行。相关版本:Chrome 108.0.5359.125,Python 3.9.12,Selenium 4.7.2。
解决方案
以下是针对该问题的具体修复步骤:
关闭所有Chrome进程
若有Chrome窗口(包括后台静默进程)正在占用你指定的用户数据目录,Selenium无法获取独占访问权,会触发该错误。打开任务管理器,结束所有chrome.exe进程后再运行脚本。配置文件目录权限检查
右键目标用户数据目录(如C:\Users\Rattapong.Pojpatin\AppData\Local\Google\Chrome\User Data)→ 属性 → 安全标签,确保当前用户拥有完全控制权限,避免因读写限制导致启动失败。复制配置文件到独立目录(最推荐)
直接使用默认Chrome的用户数据目录容易和手动打开的Chrome进程冲突,建议复制目标配置文件到独立目录:- 复制
C:\Users\Rattapong.Pojpatin\AppData\Local\Google\Chrome\User Data\Profile 2到新路径,比如D:\ChromeProfiles\Profile2 - 修改代码中的参数:
chrome_options.add_argument("--user-data-dir=D:\\ChromeProfiles") chrome_options.add_argument('--profile-directory=Profile2')
- 复制
适配Selenium 4.x的标准写法
Selenium 4.x已不推荐直接使用executable_path参数,改用Service类更规范,同时避免潜在兼容性问题:from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service chrome_options = Options() # 使用独立配置文件目录 chrome_options.add_argument("--user-data-dir=D:\\ChromeProfiles") chrome_options.add_argument('--profile-directory=Profile2') service = Service("D:\\Chromedriver\\chromedriver.exe") browser = webdriver.Chrome(service=service, options=chrome_options) browser.get('https://sellercenter.lazada.co.th/apps/seller/login')确认ChromeDriver与Chrome版本完全匹配
确保ChromeDriver版本为108.0.5359.125(与你的Chrome版本一致),版本不匹配也可能引发启动异常。
内容的提问来源于stack exchange,提问作者Rattapong Pojpatinya

