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

Selenium IWebDriver(ChromeDriver)遇已有Chrome窗口无法正常运行求助

问题与解决方案

问题描述

现有代码如下,仅在无其他Chrome窗口运行时能正常执行:

ChromeOptions options = new ChromeOptions();
options.AddArgument(@"user-data-dir=C:\Users\mypc\AppData\Local\Google\Chrome\User Data");
options.AddArgument(@"profile-directory=Default");

IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl(Url);

若已有Chrome窗口打开,运行代码会触发以下错误:

13.08.2024 16:52:35 session not created: Chrome failed to start: exited normally.
(session not created: 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.) (SessionNotCreated)

原因

Chrome的用户数据目录(user-data-dir)同一时间只能被一个Chrome实例占用。已打开的Chrome窗口会锁定该目录,导致ChromeDriver无法复用相同目录启动新实例,进而抛出错误。

解决方案

方案1:使用独立的用户数据目录

复制默认用户数据目录到新路径,让ChromeDriver使用这个独立目录,避免和现有Chrome实例冲突:

ChromeOptions options = new ChromeOptions();
// 指定新的用户数据目录,和默认目录分开
options.AddArgument(@"user-data-dir=C:\Users\mypc\AppData\Local\Google\Chrome\Automation User Data");
options.AddArgument(@"profile-directory=Default");

IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl(Url);

首次运行时,Chrome会在新目录生成配置文件,可手动同步书签、扩展等内容。

方案2:附加到已运行的Chrome实例

如果需要复用已打开的Chrome窗口,需先开启Chrome的远程调试端口,再让ChromeDriver连接:

  1. 关闭所有Chrome窗口,通过命令行启动Chrome并开启调试端口:
    chrome.exe --remote-debugging-port=9222
    
  2. 修改代码,让ChromeDriver连接到该端口:
    ChromeOptions options = new ChromeOptions();
    options.AddArgument(@"--remote-debugging-port=9222");
    
    IWebDriver driver = new ChromeDriver(options);
    driver.Navigate().GoToUrl(Url);
    
    此方式下,ChromeDriver会直接控制已打开的Chrome窗口,所有操作都在该窗口中执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:22:46