Search code examples
javaselenium-webdriverxpathcss-selectorsautosuggest

How to select the first auto suggestion using Selenium and Java


I am entering the name which is I want to search then it is displayed auto suggestion, but I am not able to select the first option from autosuggestion.

This is eclipse oxygen with TestNG plugin

driver.findElement(By.className("searchfilter")).sendKeys("Abilify");// This is working But after that option selection is not working

driver.findElement(By.cssSelector(".list-group-item:first-child")).click(); // Issue is here

Html code:

<li class="list-group-item list-group-item-action py-3 tabindex fs-1-1 bg-offwhite" id="indexTab1" href="970-ABILIFY" name="ABILIFY - ARIPIPRAZOLE">ABILIFY - ARIPIPRAZOLE</li>

Solution

  • Once you invoke sendKeys() with the desired text, to select the first auto suggestion you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

    • cssSelector:

      driver.findElement(By.className("searchfilter")).sendKeys("Abilify");
      new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li.list-group-item-action[name='ABILIFY - ARIPIPRAZOLE'][href$='-ABILIFY']"))).click();
      
    • xpath:

      driver.findElement(By.className("searchfilter")).sendKeys("Abilify");
      new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(@class, 'list-group-item-action') and @name='ABILIFY - ARIPIPRAZOLE'][contains(., 'ABILIFY - ARIPIPRAZOLE')]"))).click();