Write a java program to capture auto suggestions list

Write a java program to capture auto suggestions list while entering data on Google search box.

Let us search for “testingd” and capture the auto suggestions shown by Google search engine and print the results as shown in below picture. Iterator<E> is an interface is a member of Java Collections Framework. The iterator is iterated and auto suggestions are printed in a loop.

Google Auto Suggestion Box


Java sample 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