java.lang.NoSuchMethodError: org.openqa.selenium.os.CommandLine.find(Ljava/lang/String;)Ljava/lang/String; while using PhantomJS 2.1.1 with Selenium

java.lang.NoSuchMethodError: org.openqa.selenium.os.CommandLine.find(Ljava/lang/String;)Ljava/lang/String; while using PhantomJS 2.1.1 with Selenium

OS - Windows 7

PhantomJS 版本 - 2.1.1

Selenium - 3.8.1(硒服务器)。

JDK - 152.

我正在尝试 运行 简单测试,使用 PhantomJS:

1) 初始化驱动程序:

System.setProperty("phantomjs.binary.path","src\main\resources\phantomjs.exe");
WebDriver driver = new PhantomJSDriver();

2) 任何测试,让它在 en.wikipedia.org:

上验证文本 "welcome"
driver.get("http://en.wikipedia.org");
System.out.println(driver.findElement(By.xpath("//div[contains(text(),'Welcome')]")).isDisplayed());

3) 运行 测试,但收到错误:

Exception in thread "main" java.lang.NoSuchMethodError: org.openqa.selenium.os.CommandLine.find(Ljava/lang/String;)Ljava/lang/String;
    at org.openqa.selenium.phantomjs.PhantomJSDriverService.findPhantomJS(PhantomJSDriverService.java:232)
    at org.openqa.selenium.phantomjs.PhantomJSDriverService.createDefaultService(PhantomJSDriverService.java:181)
    at org.openqa.selenium.phantomjs.PhantomJSDriver.<init>(PhantomJSDriver.java:104)
    at org.openqa.selenium.phantomjs.PhantomJSDriver.<init>(PhantomJSDriver.java:94)

Google 显示,此类问题时有发生(不兼容 selenium/PhantomJS)。 问题:是否有任何解决方法可以让最后的硒和 2.1.1 PhantomJS 成为好朋友?

注意:任何其他驱动程序都可以正常工作(edge,chrome,ff)。

您看到的错误说明了一切:

NoSuchMethodError: org.openqa.selenium.os.CommandLine.find(Ljava/lang/String;)Ljava/lang/String;

Class NoSuchMethodError

NoSuchMethodError extends IncompatibleClassChangeError 并且根据 Java 文档 如果应用程序试图调用 class 的指定方法( static 或 instance),并且 class 不再具有该方法的定义。通常,此错误会被编译器捕获,并且如果 class 的定义已不兼容地更改,则此错误只会在 运行 时发生。

解决方案

执行以下步骤:

  • 将您的 JDK 更新到最新版本 (Java 8 Update 151)
  • 从 IDE.
  • 中清理 Project Space
  • 运行 CCleaner 清除所有 OS 系统杂务的工具。
  • 拍一张System Reboot
  • 仅添加 Selenium-Java Clients v3.8.1 jar.
  • 因为你正在使用 PhantomJSDriver (GhostDriver) 你需要添加以下 Maven Dependency :

    <dependency>
        <groupId>com.github.detro</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.4.0</version>
    </dependency> 
    
  • 您需要使用 phantomjs[=63 的绝对路径更新行 System.setProperty =]二进制如下:

    File path=new File("C:\path\\to\phantomjs-2.1.1-windows\bin\phantomjs.exe");
    System.setProperty("phantomjs.binary.path",path.getAbsolutePath());
    WebDriver driver= new PhantomJSDriver();
    driver.navigate().to("https://www.google.co.in/");
    
  • 执行你的Test

只是添加一个可以面对相同异常的不同场景。

在使用 Eclipse 时,下面的代码有效:

File file = new File("C://phantomjs.exe");
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
WebDriver driver = new PhantomJSDriver();

在使用 Intellij 时,上面的相同代码抛出了问题中提到的错误。

但是下面的代码与 Intellij 一起工作:

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\phantomjs.exe");

WebDriver driver = new PhantomJSDriver(capabilities);

注意:不要忘记更改exe路径。