Search code examples
javaseleniumselenium-webdriverhtml-selectselect-options

Select Selenium


I am creating a selenium test with java. I want to automize a dropdown menu in a dialogue. The xpath of the dropdown menu is:

/html/body/div[8]/div/div/form/div[2]/div[2]/div[2]/div/select

My problem is that I cant select an element from the dropdown menu. I used:

new WebDriverWait(driver, 20).until

and ExpectedCondition to select an element. Can you help me to find a way to select an element from the drop-down.


Solution

  • To select one of the from a tag you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

    • Using id and selectByIndex():

      new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("selectID")))).selectByIndex(1);
      
    • Using cssSelector and selectByVisibleText():

      new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("selectCssSelector")))).selectByVisibleText("OptionText");
      
    • Using xpath and selectByValue():

      new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("selectXpath")))).selectByValue("OptionValue");
      

    References

    You can find a couple of relevant detailed discussions in: