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

Selenium 4.11.0/4.12.1关闭WebDriver时出现连接重置异常

问题排查与修复方案

可能原因

  • Selenium 4.11.0/4.12.1默认启用W3C协议,关闭WebDriver会话时的HTTP请求因网络波动、驱动兼容性问题被服务器重置
  • ChromeDriver与Selenium版本不匹配:Selenium 4.x对浏览器驱动版本要求严格,版本错位会导致会话关闭时出现异常
  • 代码中重复调用driver.quit(),或者在调用quit前会话已被意外终止
  • Selenium内置HttpClient的超时配置不合理,导致关闭请求未完成就被断开

修复方案

  1. 严格匹配驱动与Selenium版本
    参照Selenium官方版本对应规则,确保ChromeDriver版本与使用的Selenium 4.12.1完全兼容(例如Selenium 4.12.1对应ChromeDriver 114.0.5735.90至116.x版本),替换不匹配的驱动文件。

  2. 修正WebDriver关闭逻辑
    检查代码,确保仅调用一次driver.quit(),并且在调用前确认会话处于活跃状态。示例修正后的关闭逻辑:

    if (driver != null) {
        try {
            driver.quit();
        } catch (Exception e) {
            // 捕获异常并记录日志,避免影响主流程
            log.warn("关闭WebDriver时出现异常", e);
        } finally {
            driver = null;
        }
    }
    
  3. 升级Selenium版本
    Selenium 4.13.0及后续版本已修复多个会话管理相关的bug,直接将pom.xml中的Selenium依赖版本升级到最新稳定版:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.15.0</version> <!-- 替换为最新稳定版 -->
    </dependency>
    
  4. 调整HttpClient配置(可选)
    如果无法升级版本,可显式配置Selenium的HttpClient超时参数,避免请求被过早断开:

    HttpClient.Factory httpClientFactory = HttpClient.Factory.createDefault()
        .withConnectTimeout(Duration.ofSeconds(10))
        .withReadTimeout(Duration.ofSeconds(10));
    WebDriver driver = new ChromeDriver(new ChromeOptions().setAcceptInsecureCerts(true), httpClientFactory);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:00:00