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

从Selenium3.11.0升级到4.0.0后找不到ChromeOptions的setExperimentalOption方法

问题原因及修复方案

1. 核心报错原因

你遇到的java.lang.NoSuchMethodError本质是类版本冲突:项目运行时加载的ChromeOptions类仍然是Selenium 3.x版本,该版本的setExperimentalOption方法签名和Selenium 4.x不匹配,导致找不到对应方法。

2. 第一步:清理并统一Selenium依赖

先修复pom.xml配置,避免不同版本的Selenium依赖混装:

  • 移除所有单独引入的selenium-chrome-driver、selenium-remote-driver等子依赖,统一引入全量的selenium-java依赖
  • 用dependencyManagement锁定所有Selenium相关依赖的版本为4.0.0,避免子依赖版本漂移
    pom参考配置:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-bom</artifactId>
            <version>4.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
    </dependency>
</dependencies>

修改后执行mvn clean install清空旧依赖缓存,重新拉取对应版本的包。

3. 第二步:适配Selenium 4的API写法

你当前的代码大部分已经符合Selenium 4的规范,仅需微调ACCEPT_SSL_CERTS的设置方式(Selenium 4中ChromeOptions提供了更直接的配置入口,不需要再调用通用的setCapability方法),调整后的代码如下:

WebDriver driver = new ChromeDriver(getChromeOptions());

private ChromeOptions getChromeOptions() {
    try {
        ChromeOptions options = new ChromeOptions();

        HashMap<String, Object> chromePrefs = new HashMap<>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory", fileLocation);
        options.setExperimentalOption("prefs", chromePrefs);
        options.addArguments("start-maximized");
        // Selenium 4 专用的SSL证书配置方式
        options.setAcceptInsecureCerts(true);

        return options;
    } catch (Exception e) {
        LOG.error("Exception building options", e);
    }
    return null;
}

4. 验证步骤

修改完成后先在本地执行mvn dependency:tree | grep selenium检查所有Selenium依赖的版本是否统一为4.0.0,确认无版本冲突后再运行测试即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:06:04