新版Selenium无法复用Driver?detach选项引发连接错误求解
在Selenium 4及以上版本中,默认执行完脚本后ChromeDriver会自动关闭浏览器。用options.add_experimental_option("detach", True)能让浏览器保持打开,但此时用webdriver.Remote复用之前存储的session_id和command_executor URL时,会触发如下连接拒绝错误:
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=57349): Max retries exceeded with url: /session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022FFDB034F0>: Failed to establish a new connection: [WinError 10061] No se puede establecer una conexión ya que el equipo de destino denegó expresamente dicha conexión'))
核心问题是:detach选项会让ChromeDriver进程在脚本结束后直接终止,原来的command_executor服务已经关闭,自然无法再连接。
解决方案:用Chrome调试端口替代detach选项
不要依赖detach,而是通过给Chrome指定调试端口的方式,让浏览器保持可复用状态,同时避免ChromeDriver进程提前终止。具体步骤如下:
- 启动Chrome时添加
--remote-debugging-port参数,指定一个未被占用的端口(比如9222),开启调试模式。 - 无需detach选项,调试模式下Chrome会一直保持打开,直到手动关闭。
- 复用会话时,通过
debuggerAddress参数直接连接到调试端口的Chrome实例。
修改后的启动脚本
from selenium import webdriver import openpyxl from selenium.webdriver.chrome.options import Options options = Options() # 指定调试端口,固定为9222(可自定义未被占用的端口) options.add_argument("--remote-debugging-port=9222") # 可选:指定本地Chrome用户数据目录,复用现有登录状态和配置 options.add_argument(r"--user-data-dir=C:\Users\juanb\AppData\Local\Google\Chrome\User Data") # 启动Chrome,连接到调试端口实例 driver = webdriver.Chrome(options=options) # 保存会话信息到Excel session_id = driver.session_id debug_url = "http://localhost:9222" wb = openpyxl.load_workbook("DRIVER.xlsx") sheet = wb.active sheet.cell(1, 2).value = session_id sheet.cell(2, 2).value = debug_url wb.save("DRIVER.xlsx") driver.get("https://www.google.com/?hl=es") print(f"Session ID: {session_id}") print(f"Debug URL: {debug_url}")
修改后的复用脚本
from selenium import webdriver import openpyxl from selenium.webdriver.chrome.options import Options wb = openpyxl.load_workbook("DRIVER.xlsx") sheet = wb.active session_id = sheet.cell(1, 2).value debug_url = sheet.cell(2, 2).value options = Options() # 连接到已打开的调试端口Chrome实例 options.add_experimental_option("debuggerAddress", debug_url.split("//")[-1]) # 直接初始化driver,自动关联已打开的浏览器 driver = webdriver.Chrome(options=options) # 可选:验证会话是否匹配 assert driver.session_id == session_id, "会话ID不匹配,复用失败" # 执行后续自动化操作 driver.get("https://www.example.com")
注意事项
- 调试端口要选未被占用的,若之前有Chrome实例在运行,需先关闭再启动,避免端口冲突。
- 指定
--user-data-dir可以复用你日常使用的Chrome配置(比如已登录的账号),不需要的话可以去掉,会生成临时配置文件。 - 这种方式下,Chrome会一直保持打开状态,直到你手动关闭,多个脚本都可以连接复用同一个会话。
内容的提问来源于stack exchange,提问作者Juan BZabala

