Selenium Select from Dropdown

Profile picture for user arilio666

In selenium, dropdowns can be handled and selected from the option using a class called the 'Select' class. If you spot a select tag in DOM, the select class is the one. Select class is instantiated by using the select tag selector inside the select as an argument.

Select e1 = new Select(driver.findElement(By.id("mySelect")));
  • The value in the dropdown can be selected using WebDriver's Select class. There are three techniques:
  1. selectByValue
  2. selectByVisibleText
  3. selectByIndex

Here is an example HTML code:

<select id="mySelect">
<option value="option1">One</option>
<option value="option2">Two</option>
<option value="option3">Three</option>
</select>

This can be handled by select class by:

Select e1 = new Select(driver.findElement(By.id("mySelect")));
e1.selectByValue("option1");
e2.selectByVisibleText("Three");
e3.selectByIndex(2);

Example:

Autopract site solely created for handling dropdowns is used for example, in this site.

Selenium Select from Dropdown
  • Let us try to select 'Football' by text and 'Table Tennis' by index.
  • Select's index starts from zero, so Table Tennis is in the third index. Let us check it out using the selenium code.
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://autopract.com/selenium/dropdown1/");
        driver.manage().window().maximize();
        WebElement dropD = driver.findElement(By.xpath("//select[@class='custom-select']"));
        Select e1 = new Select(dropD);
        e1.selectByVisibleText("Football");
        e1.selectByIndex(3);
  • This code will select Football first and Table Tennis from the dropdown by the third index.
  • This is how we can select from the dropdown in selenium.