You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Chrome配置文件的Selenium脚本仅在无其他Chrome窗口时正常运行

问题解决:Selenium调用Chrome配置文件时已有窗口存在导致失败

问题原因

Chrome的用户数据目录(user-data-dir)同一时间只能被一个Chrome实例占用。当你已经打开了使用该配置的Chrome窗口时,Selenium尝试启动新实例会因为无法获取目录锁而失败,触发DevToolsActivePort file doesn't exist错误。

解决方案

方法1:使用独立测试配置目录(推荐)

复制现有配置到新目录,避免和日常使用的Chrome实例冲突:

  1. 关闭所有Chrome窗口
  2. 复制C:\Users\Paul\AppData\Local\Google\Chrome\User Data\Profile 5到新路径,比如C:\Users\Paul\AppData\Local\Google\Chrome\Test Profile
  3. 修改脚本配置:
from selenium import webdriver as wd
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
# 使用独立的测试配置目录
chrome_options.add_argument(r"user-data-dir=C:\Users\Paul\AppData\Local\Google\Chrome\Test Profile")
wd = wd.Chrome('drivers/chromedriver.exe', options=chrome_options)
wd.get("你的目标URL")

方法2:启动前强制关闭Chrome进程(临时方案)

在脚本开头添加代码,确保配置目录未被占用:

import subprocess

# 强制关闭所有Chrome进程(Windows系统)
subprocess.run(["taskkill", "/F", "/IM", "chrome.exe"], capture_output=True)

# 原有Selenium代码
from selenium import webdriver as wd
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_options.add_argument(r"user-data-dir=C:\Users\Paul\AppData\Local\Google\Chrome\User Data")
chrome_options.add_argument('--profile-directory=Profile 5')
wd = wd.Chrome('drivers/chromedriver.exe', options=chrome_options)
wd.get("你的目标URL")

方法3:复用已有Chrome会话

如果需要保留已打开的Chrome窗口,先手动启动带调试端口的Chrome,再让Selenium连接:

  1. 关闭所有Chrome窗口,打开命令行执行:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\Users\Paul\AppData\Local\Google\Chrome\User Data" --profile-directory=Profile 5
  1. 修改Selenium脚本连接到该端口:
from selenium import webdriver as wd
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_options.add_argument("--remote-debugging-port=9222")
wd = wd.Chrome('drivers/chromedriver.exe', options=chrome_options)
wd.get("你的目标URL")

注意事项

  • 确保ChromeDriver版本与本地Chrome版本完全匹配,版本不兼容也会引发类似错误
  • 使用原始字符串(r"路径")避免Python解析路径中的转义字符(比如\U)

内容的提问来源于stack exchange,提问作者Jhon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:23:34