我的目的是执行无头浏览以实现测试自动化。我在Java中使用Selenium Webdriver。
现在,问题是脚本可以在Firefox浏览器中正常运行,但不能在HtmlUnitDriver中运行。
请指导我我犯错的地方。
public class Headless
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new HtmlUnitDriver();
//WebDriver driver=new FirefoxDriver();
// Navigate to Google
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=k36cVsa6OubI8Aec14bICQ&gws_rd=ssl");
//Thread.sleep(14000);
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("sb_ifc0")));
System.out.println("URL= "+driver.getCurrentUrl());
// Locate the searchbox using its name
WebElement element = driver.findElement(By.id("sb_ifc0"));
// Enter a search query
element.sendKeys("Guru99");
// Submit the query. Webdriver searches for the form using the text input element automatically
// No need to locate/find the submit button
element.submit();
// This code will print the page title
System.out.println("Page title is: " + driver.getTitle());
如果是HtmlUnitDriver,则会发生错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/gargoylesoftware/htmlunit/javascript/host/Event
at org.openqa.selenium.htmlunit.HtmlUnitDriver.resetKeyboardAndMouseState(HtmlUnitDriver.java:513)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:509)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:469)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.<init>(HtmlUnitDriver.java:185)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.<init>(HtmlUnitDriver.java:195)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.<init>(HtmlUnitDriver.java:191)
at com.se.ecoreal.selenium.Headless.main(Headless.java:15)
Caused by: java.lang.ClassNotFoundException: com.gargoylesoftware.htmlunit.javascript.host.Event
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
最佳答案
这是行不通的,因为HtmlUnitDriver默认情况下禁用了javascript。检查默认的构造函数代码:
public HtmlUnitDriver() {
this(false);
}
public HtmlUnitDriver(boolean enableJavascript) {
this(BrowserVersion.getDefault(), enableJavascript);
}
如果启用javascript,您的示例对我有用:
WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_38, true);
编辑(已编辑问题的答案):
NoClassDefFoundError是由缺少(或版本错误)依赖项引起的。如果使用的是maven或gradle,请检查项目是否存在依赖项冲突。如果不使用依赖项管理,请确保包含所有HtmlUnit依赖项。