How to Handle Autocomplete Textbox in Selenium WebDriver?

Now a days, Most of the Web Applications providing the Autocomplete Suggestion Dropdown box to the user. Basically it helps the user to find the exact option they are looking for, based on the text they entered in the Search box.

But as an Automation Tester, How to Handle Autocomplete dropdown in Selenium WebDriver?

So in this Post, We will try to Handle AutoComplete Google Places Dropdown using Selenium WebDriver. After this post you will be able to automate any autocomplete suggestion box.

This is the Scenario for which we create Selenium Script:
1. Open the browser.
2. Enter the url: https://twoplex.com
3. Go to Live Posting and Select the autocomplete text box.
4. Select the text from Dropdown Display options.

You can try the below Selenium Java Code and run in your system.

				
					import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class AutomateGooglePlaceDropdown {

	public static void main(String[] args) throws InterruptedException {
		
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Rajeev\\eclipse-workspace\\LoginFormScript\\Driver\\chromedriver.exe");
		ChromeDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		//launch the website
		driver.get("https://www.twoplugs.com/");

		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
		//find the element
		driver.findElement(By.xpath("//a[text()='Live Posting']")).click();
		
		//Search Box webelement
		WebElement searchBox = driver.findElement(By.id("autocomplete"));
		
		//CLear the text inside the search bar
		searchBox.clear();
		
		//Enter the text you want to search
		searchBox.sendKeys("Gurgaon"); 

		String text;

		
		//This method find the exact Text in Autocomplete dropdown suggestion
		do {
			
			//this will select the first option
			searchBox.sendKeys(Keys.ARROW_DOWN);
			
			//this will get the value of first option
			text = searchBox.getAttribute("value");
			
			//this will compare the text we want in suggestion box
			if (text.equals("Gurgaon - Sohna Road, Block S, Sispal Vihar, Sector 47, Gurugram, Haryana, India")) {
				searchBox.sendKeys(Keys.ENTER);
				break;
			}
			Thread.sleep(3000);
		} while (!text.isEmpty());

		driver.close();
	}

}

				
			
Facebook
Twitter
LinkedIn
WhatsApp
Print

Leave a Comment