How to select an option from a dynamic dropdown using Selenium?

user2377826 picture user2377826 · Jul 7, 2018 · Viewed 21k times · Source

I am trying to click on dropdown value to select city in from field in Make my trip http://www.makemytrip.com/. But getting Stale element reference exception. Ids are getting changed on page load. Tried below code:

driver.findElement(By.xpath(".//*[@id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[@id='ui-id-1']"));
driver.findElement(By.xpath(".//*[@id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeSelected(driver.findElement(By.xpath(".//*[@class='ui-menu-item'][2]"))));

Answer

DebanjanB picture DebanjanB · Jul 7, 2018

To click on a dropdown value e.g. Mumbai you can use the following solution:

  • Code Block:

    driver.get("https://www.makemytrip.com/")
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='input_fromto checkSpecialCharacters ui-autocomplete-input' and @id='hp-widget__sfrom']"))).click();
    List<WebElement> myList = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[@class='ui-menu-item'][starts-with(@id,'ui-id-')]//span[@class='autoCompleteItem__label']")));
    for (WebElement element:myList)
        if(element.getText().contains("Mumbai"));
            element.click();
    
  • Browser Snapshot:

from_mumbai