Wednesday, 3 July 2013

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 .
  1. import java.util.Iterator;  
  2. import java.util.List;  
  3. import java.util.concurrent.TimeUnit;  
  4. import org.openqa.selenium.By;  
  5. import org.openqa.selenium.WebDriver;  
  6. import org.openqa.selenium.WebElement;  
  7. import org.openqa.selenium.firefox.FirefoxDriver;  
  8. import org.testng.annotations.BeforeTest;  
  9. import org.testng.annotations.Test;  
  10.   
  11. public class SearchSuggestion {  
  12.    
  13. WebDriver driver;  
  14.    
  15.  @BeforeTest  
  16.  public void start(){  
  17.    driver = new FirefoxDriver();   
  18.  }  
  19.     
  20.  @Test  
  21.   public void SearchSuggestion() {  
  22.     
  23.   driver.get("http://google.com");  
  24.   driver.findElement(By.id("gbqfq")).sendKeys("vam");  
  25.   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
  26.     
  27.    WebElement table = driver.findElement(By.className("gssb_m"));   
  28.    List<webelement> rows = table.findElements(By.tagName("tr"));   
  29.    Iterator<webelement> i = rows.iterator();   
  30.    System.out.println("-----------------------------------------");   
  31.    while(i.hasNext()) {   
  32.            WebElement row = i.next();   
  33.            List<webelement> columns = row.findElements(By.tagName("td"));   
  34.            Iterator<webelement> j = columns.iterator();   
  35.            while(j.hasNext()) {   
  36.                    WebElement column = j.next();   
  37.                    System.out.println(column.getText());   
  38.            }   
  39.            System.out.println("");   
  40.               
  41.    System.out.println("-----------------------------------------");   
  42.    }   
  43.   }   
  44. }</webelement></webelement></webelement></webelement>  

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

No comments:

Post a Comment

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...