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

Python Selenium Chrome驱动连接拒绝错误捕获与进程清理求助

解决方案

1. 修正异常捕获范围,确保Driver始终被清理

你的核心问题有两个:一是Driver初始化代码在try块外,导致初始化阶段的连接异常无法被捕获;二是当Driver连接已断开时,直接调用quit()可能抛出新异常,导致进程残留。以下是修复后的代码:

from selenium.common.exceptions import WebDriverException
import http.client
import os

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(
    "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--lang=en-GB")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')  # 解决Linux资源限制问题
chrome_options.add_argument('--proxy-server={}'.format(proxy))

driver = None
try:
    driver = webdriver.Chrome(service=CHROMEDRIVER_PATH, options=chrome_options)
    # 执行你的WebDriver操作逻辑
except (WebDriverException, ConnectionRefusedError, http.client.RemoteDisconnected) as e:
    print(f"异常信息: {str(e)}")
finally:
    # 确保无论是否异常,都尝试清理Driver
    if driver is not None:
        try:
            driver.quit()
        except Exception as quit_err:
            print(f"Driver退出失败: {str(quit_err)}")
            # 强制清理Chrome残留进程(Linux环境)
            os.system("pkill -f chrome")
            # Windows环境替换为:os.system("taskkill /f /im chrome.exe /im chromedriver.exe")

2. 用上下文管理器简化Driver生命周期管理

Selenium WebDriver支持上下文管理器(with语句),会自动在代码块结束后调用quit(),无需手动处理:

from selenium.common.exceptions import WebDriverException
import http.client
import os

chrome_options = webdriver.ChromeOptions()
# 重复上述options配置...

try:
    with webdriver.Chrome(service=CHROMEDRIVER_PATH, options=chrome_options) as driver:
        # 执行你的WebDriver操作逻辑
except (WebDriverException, ConnectionRefusedError, http.client.RemoteDisconnected) as e:
    print(f"异常信息: {str(e)}")
    # 连接断开时强制清理残留进程
    os.system("pkill -f chrome")

关键说明

  • 捕获特定异常:显式捕获Selenium的WebDriverException(所有WebDriver相关异常的基类)和底层连接异常(ConnectionRefusedError、RemoteDisconnected),避免遗漏。
  • 双重异常防护:在finally块中对quit()额外加一层异常捕获,防止Driver已断开时调用quit()抛出新异常,导致进程无法清理。
  • 强制进程清理:如果quit()失效,直接用系统命令杀死Chrome相关进程,彻底解决残留问题。
  • 版本匹配:确保ChromeDriver版本与本地Chrome浏览器版本完全一致,这是连接异常的最常见原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:05:29