DDM
DDM

Reputation: 113

Selenium Google Places Autocomplete Java

I am trying to automate Google auto suggestion and selecting a random suggestion using Selenium.

WebElement element = driver.findElement(By.xpath("//input[@id='id_address']"));
element.sendKeys(“whi”);

How to select a random suggestion from the list of Google suggestions ?

Upvotes: 1

Views: 2455

Answers (1)

Aaron Davis
Aaron Davis

Reputation: 1731

First you need to find all the matching elements that represent auto-complete suggestion options. Since the appearance of auto complete suggestions is asynchronous, you need to wait for them to appear using a loop or a WebDriverWait. The line that gets the List<WebElement> list will keep trying to find elements that match the given selector and will only return when the list (from the driver.findElements call that it wraps) is not empty. If it doesn't find a non-empty list in the given timeout (10 seconds in this case from the WebDriverWait constructor) it will throw a TimeoutException. Then, once you have the list of suggestions, it's a simple matter of selecting a random one from that list and clicking on it.

driver.get("https://www.google.com");
driver.findElement(By.name("q"))
      .sendKeys("whi");
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("[role='option']"), 0));
int index = (int) (Math.random() * options.size());
options.get(index)
       .click();

Upvotes: 1

Related Questions