无头 driver

Headless driver

代码:

import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import com.gargoylesoftware.htmlunit.BrowserVersion;

public class Test {

public static void main(String[] args) {

    //System.out.println(JavaUtils.getMonthOldDate());
    HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
    driver.setJavascriptEnabled(true);
    driver.get("https://www.google.com");
    System.out.println(driver.getTitle());
    driver.quit();

    }

}

控制台异常:

Exception in thread "main" java.lang.NoSuchFieldError: DISMISS_AND_NOTIFY
at org.openqa.selenium.htmlunit.HtmlUnitDriver.<init>(HtmlUnitDriver.java:225)
at testCases.Test.main(Test.java:16)

从以下位置下载 jar:https://jar-download.com/?search_box=selenium-htmlunit-driver

我使用了这段代码,没有收到任何错误。输出为 Google

也许您需要下载最新的 chrome driver、chrome 浏览器版本和 Selenium。

我的配置:

Chrome: Version 67.0.3396.99 (Official Build) (64-bit)
3.12.0 (you can go for 3.13.0 also)
Chrome driver : version 2.40

下载链接:Chrome_driver
Selenium 3.13.0 浏览器你可以升级。

我在这里尝试了这个简单的代码示例,它对我有用:

   import org.openqa.selenium.By;
   import org.openqa.selenium.htmlunit.HtmlUnitDriver;
   import org.testng.Assert;
   import org.testng.annotations.Test;

    public class TestHtmlHeadless {

        @Test
        public void runHtmlHeadless() {
            String URl = "http://checkip.dyndns.com/";

            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(true);

            Assert.assertTrue(!isEmpty(driver), "Driver should not be empty!");

            driver.get(URl);

            System.err.println("Open Page: " + URl);

            String ip = driver.findElement(By.cssSelector("body")).getText();
            System.out.println("Debug: " + ip);

            Assert.assertTrue(!isEmpty(ip));
        }



        public static boolean isEmpty(Object val) {
            if (val == null) {
                return true;
            }
            return false;
        }
    }

尝试使用 maven 或 gradle 来获取,下面是 maven pom.xml 文件并在 maven 性质中使用它,它会工作:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-htmlunit-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-htmlunit-driver</artifactId>
        <version>2.52.0</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8</version>
        <scope>test</scope>
    </dependency>
</dependencies>

结果:

或在此处下载 html-驱动程序:https://github.com/SeleniumHQ/htmlunit-driver/releases