How to handle Auto Suggestions in Selenium WebDriver

23 March, 2014
In a textbox if we type a few letters then it will automatically display a list of available options which start with the typed letters. This is called as Auto-Suggestion which looks like a dropdown list but it cannot be handled using Select class.

In order to handle Auto Suggestion we first type the required text in the text box using sendkeys() which will type the given text and the Auto Suggestion will be displayed. In order to identify the options present in Auto Suggestion most of the cases we use CSS/XPath selector and in order to select required option we use click().

Below is the code to print the Auto-Suggestions on the screen displayed on Google when we type Selenium.

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;

public class AutoSuggestions {
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		driver.get("http://www.google.com");
		driver.findElement(By.id("gbqfq")).sendKeys("selenium");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		List allOptions = driver.findElements(By.xpath("//td/span[text()='selenium']"));
		
		for (int i = 0; i < allOptions.size(); i++) {
			String option = allOptions.get(i).getText();
			System.out.println(option);
		}
	}
}

If the element is dynamically changing then we identify them using its parent element.


No comments:

Post a Comment