Search code examples
seleniumselenium-webdriverhtmlunit-driver

Difficult to run the script in selenium webdriver which contains HtmlUnitDriver


I am unable to run the basic selenium script which contains the HtmlUnitDriver. If I try to run the code I get the following error.

Code:

public class SampleUnitDriver  
{   
    public static void main(String[] args) throws Exception 
    {
        HtmlUnitDriver unitDriver = new HtmlUnitDriver(); 

        unitDriver.get("http://google.com");

        System.out.println("Title of the page is -> " + unitDriver.getTitle());             

        Thread.sleep(3000L);
        WebElement searchBox = unitDriver.findElement(By.className("gsfi"));

        searchBox.sendKeys("Selenium");             

        WebElement button = unitDriver.findElement(By.name("gbqfba"));

        button.click();

        System.out.println("Title of the page is -> " + unitDriver.getTitle());

    } 
}

Error:

    Title of the page is -> Google
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Returned node was not a DOM element
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'user-PC', ip: '192.168.1.52', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: driver.version: SampleUnitDriver
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByCssSelector(HtmlUnitDriver.java:1060)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByClassName(HtmlUnitDriver.java:1032)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1725)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1721)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1367)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1721)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:606)
    at com.digitalmqc.automation.action.SampleUnitDriver.main(SampleUnitDriver.java:16)

Solution

  • The class name gsfi of the input box is generated by javascript so you have 2 options:

    Easy One: Just select it by using the id lst-ib

    Better One: Wait for the element to be fully interactive. The reason behind this one being better is that you are trying to input text into the box which javascript plays a role. The former option may throw some unexpected errors.