Automation Using Selenium Webdriver
Showing posts with label Getting google search auto suggestions using Webdriver(Selenium 2). Show all posts
Showing posts with label Getting google search auto suggestions using Webdriver(Selenium 2). Show all posts

Monday 24 October 2016

Getting google search auto suggestions using Webdriver(Selenium 2)

Getting google search auto suggestions using Webdriver(Selenium 2)

In the google search when we start typing any search query google will start auto suggestions. All these search suggestions are part of a WebTable. If we would like to capture all these search suggestions then we have to just iterate through the table.

Here is the sample code which will start typing "vam" and then capture all search suggestions .
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SearchSuggestion {
 
WebDriver driver;
 
 @BeforeTest
 public void start(){
   driver = new FirefoxDriver(); 
 }
  
 @Test
  public void SearchSuggestion() {
  
  driver.get("http://google.com");
  driver.findElement(By.id("gbqfq")).sendKeys("vam");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
   WebElement table = driver.findElement(By.className("gssb_m")); 
   List rows = table.findElements(By.tagName("tr")); 
   Iterator i = rows.iterator(); 
   System.out.println("-----------------------------------------"); 
   while(i.hasNext()) { 
           WebElement row = i.next(); 
           List columns = row.findElements(By.tagName("td")); 
           Iterator j = columns.iterator(); 
           while(j.hasNext()) { 
                   WebElement column = j.next(); 
                   System.out.println(column.getText()); 
           } 
           System.out.println(""); 
            
   System.out.println("-----------------------------------------"); 
   } 
  } 
}

Here is what we will see in the browser after running the above code.