Selenium WeDdriver - Automate Google Search using Explicit Wait

In this post you will learn to automate Google Search using Selenium Webdriver with Java. This is a real time example of Explicit wait command. Google search is an ajax call. We will handle this ajax call using Explicit wait command of selenium Webdriver.



What is ajax?
Ajax stands for Asynchronous Javascript and XML. Ajax is a new technology for creating for faster and more interactive web applications. What ajax does is:
  • Update a web page without reloading/refresh it
  • Read data from the server after the page is loaded
Google search is a best example of ajax. In case of google search, you simply type keyboard in search bar and just below the search bar a suggestion box with matching suggestions appears instantly, this is ajax. We can handle ajax in Selenium webdriver with the use of Explicit Wait command. I have shared below the code for automating Google search. But I recommend to execute below test case manually first and then automate it.



Test Steps:
  1. Launch the Firefox.
  2. Opens google.com
  3. Type "selenium tutorials techlistic" in search bar
  4. Wait for ajax suggestion box to appear
  5. Print all the suggestions one by one
Program Example:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class AjaxGoogleSearch {

 WebDriver driver;

  @BeforeMethod
  public void start(){
    driver = new FirefoxDriver();
  }

 @Test
 public void testGoogleSearch() {
    // Open google.com
    driver.get("http://www.google.com");
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    
    // Enter "techlistic selenium tutorials" in google search box
    driver.findElement(By.name("q")).sendKeys("selenium tutorials techlistic");    
    // Wait for suggestions box to be appear for 20 seconds
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.className("sbdd_b")));
    
    WebElement list = driver.findElement(By.className("sbdd_b"));
    List rows = list.findElements(By.tagName("li"));
    
    // Iterate over suggestions box and print suggestions one by one
    for (WebElement elem : rows) {
        System.out.println(elem.getText());
    }
 }
}




Refer Selenium Webdriver Tutorials Series

Join Telegram channel at https://t.me/techlistic
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Top 25 Must to know Selenium Webdriver Commands List

Assignment 5: Automate "Buy Product" Functionality for E-commerce Website using Selenium

Selenium Essentials - How to become expert in Automation Testing?

Selenium WebDriver - Browser and Navigation Commands