Selenium + Java · Lesson 22 of 44

0/44 done

Module 22: Dropdowns

22. Automating HTML Select & Custom Dropdown Widgets

16 minlesson

Your task

Implement selectByTextSafe:

  1. Accept WebElement element and String visibleText.
  2. Initialize Select select = new Select(element).
  3. Call select.selectByVisibleText(visibleText).

Write it in the editor, then press Check answer (Ctrl + Enter).

Selenium Select Class

java
import 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();

Key Takeaways & Walkthrough Summary

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.

Common Doubts & Lesson Q&A

Can I use the Select class on a React or Bootstrap div dropdown?

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.

Java
Skip