我的目的是为测试自动化执行无头浏览。我正在使用带有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
答案 0 :(得分:3)
它不起作用,因为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依赖关系。