How to wait for options in a select to be populated in Selenium?

Software TestingAutomation TestingSelenium Web Driver

We can wait for options in a select tag to be populated with Selenium. This can be done with the explicit wait concept in synchronization. The explicit wait is designed on the expected condition for an element.

To wait for the options, we shall verify if presenceOfNestedElementsLocatedBy is available within the explicit wait time. We shall implement the entire verification within the try catch block.

Let us see if the options are available for selection in the Continents dropdown. The ExpectedCondition along with WebDriverWait is used for explicit wait.

HTML code of the select dropdown.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SelectOptWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm");
      //expected condition presenceOfNestedElementsLocatedBy on options
      WebDriverWait w = new WebDriverWait(driver,3);
      try {
         w.until(ExpectedConditions
         .presenceOfNestedElementsLocatedBy
         (By.xpath("//select[@name='continents']"), By.tagName("option")));
         // identify dropdown
         WebElement l = driver.findElement(By.xpath("//select[@name='continents']"));
         // select option by Select class
         Select s = new Select(l);
         // selectByVisibleText to choose an option
         s.selectByVisibleText("Africa");
      }
      catch(Exception e) {
         System.out.println("Options not available");
      }
      driver.quit();
   }
}
raja
Published on 30-Nov-2020 10:16:28
Advertisements