Selenium + Java · Lesson 22 of 44
Module 22: Dropdowns
Your task
Implement selectByTextSafe:
Write it in the editor, then press Check answer (Ctrl + Enter).
Select Classimport org.openqa.selenium.support.ui.Select;
WebElement dropdownElement = driver.findElement(By.id("country-dropdown"));
Select countrySelect = new Select(dropdownElement);
// Selection options:
countrySelect.selectByVisibleText("United States");
countrySelect.selectByValue("US");
countrySelect.selectByIndex(1);
// Verifying selected option:
String chosen = countrySelect.getFirstSelectedOption().getText();Selecting dropdown options is a daily testing task. For standard HTML select tags, Selenium provides the specialized Select class. In this lesson, you will learn to select by visible text, value, and index, and handle custom div-based dropdowns. Let's master dropdowns!
Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.
No! The Select class works ONLY on standard HTML <select> tags. For custom div/ul dropdowns, click the dropdown to expand and click the target option WebElement.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___