All Posts

Java program to capture auto suggestions

Java program to capture Auto Suggestions

Write a Java program to capture the auto-suggestions list while entering data on the Google search box.  Let us search for “testingd” capture the suggestions shown by the Google search engine and print the results as shown in the below picture. Iterator<E> is an interface that is a member of the Java Collections Framework. The iterator is iterated and suggestions are printed in a loop.

 

Google Auto Suggestion Box

 

Auto Suggestions program

package com.testingdocs.examples.selenium;

import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AutoSuggestionsExample {
    public WebDriver driver = null;

    @BeforeClass
    public void initBrowser() {
        System.setProperty("webdriver.gecko.driver", 
"drivers/geckodriver.exe");
        driver = new FirefoxDriver();

    }

    @Test
    public void Search() throws Throwable {

        driver.navigate().to("https://www.google.com");
        driver.findElement(By.name("q")).clear();
        driver.findElement(By.name("q")).sendKeys("testingd");
        WebDriverWait wait = new WebDriverWait(driver, 120);
        wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.
                cssSelector(".sbsb_a li"), 0));

        List<WebElement> suggestionItems = driver.findElements(By.
                cssSelector(".sbsb_a li"));

        Iterator<WebElement> i = suggestionItems.iterator();
        System.out.println("Print suggestions for the search box.");
        while(i.hasNext())
        {
            WebElement element = i.next();
            System.out.println(element.getText());
        }

    }

    @AfterClass
    public void closeBrowser() {
        driver.quit();
    }

}

 

Auto suggestions Test method Java

Output of the program

Print suggestions for the search box.
testing definition
testing deliverables
testing data
testing documents
testing details
testing data warehouse
testing designations
testing demand in market
testing documents list
testing domain

 

Auto Suggestion List Selenium