Tuesday, October 28, 2014

Selenium HtmlUnitDriver Example

All of you may have used Seleniums FirefoxDriver or ChromeDriver for web application automation. When using them you know a browser window is opened visibly. If you do not need to visually examine the process and just need to check a final result you can use the HtmlUnitDriver instead. This consumes less memory and it is super fast when comparing with above browser drivers.
In a previous tutorial I showed you how to use FirefoxDriver to automation google search. Now I am going to show you how to do a google search invisibly using HtmlUnitDriver and get the search result page title and search result count.
If you do a google search using a browser, you know it displays the result count at the top of the result page. If you inspect the source of this page you will see that the id of the div in which this text is displayed is "resultStats". We are going to use this id to get the total time.

1. Create a new java project and name it as SeleniumLearn
2. Download the Selenium library from Selenium Download Page and add to the project
3. Add a new Java class and name it as SeleniumExample
4. Modify the class as below.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class SeleniumExample  {
    public static void main(String[] args) {

        WebDriver driver = new HtmlUnitDriver();
        driver.get("http://www.google.com");
        //The name of the google search text box is "q". 
        //You can find this by looking at the html source of the google search page.
        //Webdriver can find the search text box by that name as below
        WebElement searchBox = driver.findElement(By.name("q"));

        //Enter the search text
        searchBox.sendKeys("fast cars");
        //Below command will submit the form to which the searchBox belongs
        searchBox.submit();
        //We can get the title of the result page as below
        System.out.println("Page title : " + driver.getTitle());
        //We can get the result count as below
        WebElement resultCount = driver.findElement(By.id("resultStats"));
        System.out.println("Result Count : " + resultCount.getText());
        
        //Close the driver
        driver.quit();
    }
}

5. Now run this file and you will see the page title and the search result count printed on the console.

No comments:

Post a Comment