'Autocomplete section in Selenium

I have the list which has multiple links under each section. Each section has different links. I need to click a particular link under each section. I have written the below code but when it executes, I'm not able to click the second section of autocomplete field after clicking the first section autocomplete field. Here is my code. By using for-each am not able to select the second autocomplete field.

public class Autocomplete {
    
public static WebDriver driver;

public static void main(String[] args) throws InterruptedException {
    
    ChromeOptions option = new ChromeOptions();
    
    option.addArguments("--disable-notifications");
    
    System.setProperty("webdriver.chrome.driver",".//src//browser//chromedriver.exe");

    driver = new ChromeDriver(option);
    
    driver.manage().window().maximize();
    
    System.out.println("Browser Launch chrome");
    
    driver.get("https://www.redbus.in/");
    
    driver.findElement(By.xpath("//*[@id=\"src\"]")).sendKeys("ta");
    
    AutocompleteRedbus.RebBus(By.xpath("//*[@id=\"src\"]"), "Tambaram, Chennai");
    
    Thread.sleep(5000);
    
    driver.findElement(By.xpath("//*[@id=\"dest\"]")).sendKeys("pon");
    
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    
    AutocompleteRedbus.RebBus(By.xpath("//*[@id=\"dest\"]"), "Ponamaravathi");  
}

}

Above mentioned AutocompleteRedbus calling method code here:

public class AutocompleteRedbus extends Autocomplete{


public static void RebBus(By xpath , String text) throws InterruptedException {
                   
    List<WebElement> listOfLinks = driver.findElements(By.xpath("xpath"));
    listOfLinks.forEach(link -> {
        if (link.getText().equalsIgnoreCase("text")) {
            link.click();
            }
        });
    }
  }


Solution 1:[1]

When you are trying to select the value from the autocompleter, the xpath you are using is incorrect. Please change the xpath with the one i am providing and it would work fine.

AutocompleteRedbus.RebBus(By.xpath("//li[contains(@select-id,'results')]"), "Tambaram, Chennai");

And same for the destination method, like:

AutocompleteRedbus.RebBus(By.xpath("//li[contains(@select-id,'results')]"), "Ponamaravathi");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sameer Arora