非headless模式下Selenium ChromeDriver加载user profile遇DevToolsActivePort错误
问题描述
Chrome版本:Version 114.0.5735.91 (Official Build) (64-bit)
尝试通过Selenium ChromeDriver加载预定义用户配置文件,期望在非headless可视模式下运行脚本的同时,正常使用Chrome浏览器,但执行过程中出现异常。
使用的代码如下:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument(r"--user-data-dir=C:/Users/<User>/AppData/Local/Google/Chrome/User Data") options.add_argument(r"--profile-directory={}".format("Profile 5")) driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
执行时,Chrome会打开并显示已登录到Profile 5,但约两秒后抛出以下异常(此时Selenium打开的浏览器仍保持打开状态):
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
切换到headless模式(添加options.add_argument('headless'))后一切正常;非headless模式下不加载用户配置文件也能正常运行。
需求:实现非headless模式下加载用户配置文件的同时,仍能正常使用Chrome浏览器。
解决方案
核心问题是Selenium使用的用户数据目录与你当前正在使用的Chrome进程共享,导致目录锁冲突,引发DevTools端口异常。以下是两种可行解决方法:
方法1:复制配置文件到独立目录
这是最稳定的方案,彻底隔离Selenium和手动Chrome的配置:
- 关闭所有Chrome窗口
- 找到目标配置文件夹:
C:/Users/<User>/AppData/Local/Google/Chrome/User Data/Profile 5 - 将整个
Profile 5文件夹复制到新的独立目录,比如C:/ChromeProfiles/Profile 5 - 修改代码中的参数:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() # 指向包含复制后配置文件的父目录 options.add_argument(r"--user-data-dir=C:/ChromeProfiles") # 指定复制后的配置文件夹名称 options.add_argument(r"--profile-directory=Profile 5") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
方法2:指定独立调试端口
如果不想复制配置文件,可通过指定独立端口避免进程冲突:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument(r"--user-data-dir=C:/Users/<User>/AppData/Local/Google/Chrome/User Data") options.add_argument(r"--profile-directory=Profile 5") # 指定未被占用的独立调试端口,9222为示例,可替换为其他端口 options.add_argument("--remote-debugging-port=9222") # 禁用共享内存,避免端口相关冲突 options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
注意:如果指定的端口被占用,更换为其他未使用的端口即可。
额外注意事项
- 运行脚本前,确保没有手动打开的Chrome进程正在使用你指定的配置文件(比如手动Chrome不能同时开启Profile 5)
- 若使用方法1,后续需要更新配置(如登录新账号),需在Selenium打开的浏览器中操作,或复制回原目录替换
内容的提问来源于stack exchange,提问作者Master
相关产品推荐
相关产品推荐

