异常在线程 “main” java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver

2022-09-04 03:20:35

我已经在我的pom中添加了最新的硒依赖性.xml

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

我用我的pom在目录中运行了mvn干净安装.xml并且我还根据Selenium文档在我的应用程序类中导入了正确的类

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

但是,当我尝试运行我的主方法时,我得到以下错误

Exception in thread "main" java.lang.NoClassDefFoundError: 
org/openqa/selenium/WebDriver

我查看我的~/.m2/repository文件夹,我没有看到openqa文件夹,而是看到一个seleniumhq文件夹。

为什么 maven 没有安装 openqa 文件夹,为什么文档说要从 org.openqa 导入...当它从未存在于我的jar存储库中时。我非常困惑,我只是希望能够成功地导入硒Webdriver,同时将其放在我的本地存储库中。


答案 1

首先,正确检查程序是否具有所有重要的依赖项。
其次,我在运行 maven 项目时遇到了类似的错误:

Caused by: java.lang.NoClassDefFoundError: org/openqa/selenium/JavascriptExecutor

这个问题是因为插件不合适,因为我测试了不同版本的Selenium,它没有帮助我。

所以当我改变:maven-jar-plugin

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
 <configuration>
   <archive>
        <manifest>
             <addClasspath>true</addClasspath>
             <classpathPrefix>lib/</classpathPrefix>
             <mainClass>your_main_class</mainClass>
        </manifest>
   </archive>
 </configuration>
</plugin>

到插件:maven-shade-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
       <execution>
            <phase>package</phase>
            <goals>
               <goal>shade</goal>
            </goals>
            <configuration>
                 <transformers>
                    <transformer 
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>your_main_class</mainClass>
                    </transformer>
                 </transformers>
             </configuration>
       </execution>
    </executions>
</plugin>

问题消失了。您可以在此处找到插件之间的区别。


此外,有时即使使用相同的方法名称,我们也会升级库。由于版本不同,当一个库与此类升级不兼容时,我们在运行时获得NoClassDefFoundErrorNoSuchMethodError

Java 构建工具和 IDE 还可以生成依赖关系报告,告诉您哪些库依赖于该 JAR。大多数情况下,识别和升级依赖于旧版 JAR 的库可以解决问题。


总结一下:

  • 尝试更改硒的版本,如果它包含所有依赖项;
  • 如果您没有依赖项,请尝试添加必要的依赖项;
  • 尝试检查maven的文件夹,如果它有或没有说什么说特定的错误;
  • 尝试玩插件,如果上面没有任何帮助。

答案 2

在 Eclipse IDE 中遇到此错误。在 Eclipse 中,转到项目属性,在 Java 构建路径中,只需在类路径中添加硒罐,而不是模块路径。然后在顶部的“项目”选项卡下,执行“清理”以删除较早的buiid,然后执行“运行”。


推荐