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

Python Selenium连接已有Chrome浏览器报错:目标机器主动拒绝连接

问题解决:Selenium连接已打开Chrome报错的修复方案

错误原因

你当前的代码逻辑存在问题:先创建本地Chrome Driver实例,再通过Remote连接同一个会话,但紧接着调用driver.close()直接销毁了该会话,后续设置session_id时,目标会话已经不存在,因此出现"连接被拒绝"的错误。

正确操作步骤

要连接已打开的Chrome,需先手动启动Chrome并开启远程调试端口,再用Selenium对接该端口:

  1. 启动带远程调试的Chrome
    打开命令提示符,执行Chrome启动命令(替换为你的Chrome安装路径):

    "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir="C:\ChromeDebugProfile"
    
    • --remote-debugging-port:指定调试端口(可自定义,比如9222)
    • --user-data-dir:指定独立的用户数据目录,避免与现有Chrome进程冲突
  2. 编写Selenium连接代码
    用以下代码对接已打开的Chrome实例:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    # 对接远程调试端口
    chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    # 连接已运行的Chrome
    driver = webdriver.Chrome(options=chrome_options)
    
    # 执行后续操作
    driver.get("https://www.google.com")
    

关键注意事项

  • 确保代码中的debuggerAddress端口与启动Chrome时指定的--remote-debugging-port一致
  • 必须指定--user-data-dir,否则Chrome会复用现有进程,导致远程调试端口无法正常监听
  • 连接成功后不要随意调用driver.close(),除非你确实需要关闭当前窗口(若为唯一窗口,会话会直接终止)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:50:38