My purpose to execute headless browsing for test-automation. I am using selenium webdriver with Java.
Now, issue is script is working fine in Firefox browser,but not in HtmlUnitDriver.
Please guide me where I did mistake.
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());
The error in case of 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
It doesn't work because javascript is disabled by default for HtmlUnitDriver. Check the default constructor code:
Your example works for me if I enable javascript:
Edit (answer to the edited question):
NoClassDefFoundError is caused by a missing (or wrong version) dependency. If you are using maven or gradle, check your project for dependency conflicts. If you don't use dependency management, make sure you included all HtmlUnit dependencies.