The Select class helps you easily pick options from dropdown menus on web pages. It makes choosing items simple and clear.
0
0
Select class for dropdowns in Selenium Java
Introduction
When you need to select a country from a list on a signup form.
When testing a website's language selection dropdown.
When verifying that the correct options appear in a dropdown menu.
When automating filling out forms with dropdown fields.
When checking that selecting an option triggers the right page behavior.
Syntax
Selenium Java
Select select = new Select(WebElement dropdownElement); select.selectByVisibleText("OptionText"); // or select.selectByValue("optionValue"); // or select.selectByIndex(index);
You first create a Select object by passing the dropdown WebElement.
Use selectByVisibleText to pick by what the user sees.
Examples
Selects the option "Canada" from the dropdown with id "country".
Selenium Java
Select select = new Select(driver.findElement(By.id("country"))); select.selectByVisibleText("Canada");
Selects the option with value attribute "en" from the dropdown named "language".
Selenium Java
Select select = new Select(driver.findElement(By.name("language"))); select.selectByValue("en");
Selects the third option (index starts at 0) from the dropdown with id "colors".
Selenium Java
Select select = new Select(driver.findElement(By.cssSelector("select#colors"))); select.selectByIndex(2);
Sample Program
This test opens a webpage with a dropdown, selects "Canada" by visible text, then prints the selected option to confirm.
Selenium Java
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; public class DropdownTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/form"); WebElement dropdown = driver.findElement(By.id("country")); Select select = new Select(dropdown); select.selectByVisibleText("Canada"); String selected = select.getFirstSelectedOption().getText(); System.out.println("Selected option: " + selected); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Make sure the dropdown element is a <select> tag; Select class works only with <select> elements.
Always quit the driver to close the browser after the test.
Use explicit waits if the dropdown loads dynamically to avoid errors.
Summary
The Select class simplifies choosing options from dropdown menus.
Use selectByVisibleText, selectByValue, or selectByIndex to pick options.
Works only with <select> HTML elements.