Handling Dropdowns
RecipeBox's Add Recipe form has a categoryDropdown — a real HTML <select> element with options like "Breakfast", "Main Course", and "Dessert". Clicking a <select> directly with click() just opens it; Selenium gives you a dedicated helper, the Select class, for actually choosing an option.
The Select Class
Import it, then wrap it around the <select> WebElement:
import org.openqa.selenium.support.ui.Select;
WebElement dropdownElement = driver.findElement(By.id("categoryDropdown"));
Select categoryDropdown = new Select(dropdownElement);
selectByVisibleText()
The most readable and most commonly used option — matches the text the user actually sees in the dropdown.
categoryDropdown.selectByVisibleText("Main Course");
selectByValue()
Matches the underlying value attribute of the <option> tag, which may differ from its visible text (e.g. <option value="main">Main Course</option>).
categoryDropdown.selectByValue("main");
selectByIndex()
Selects by position, zero-based. Fragile if options get reordered, but occasionally useful for "just pick something" scenarios.
// Selects the 2nd option in the list (index 0 is the 1st)
categoryDropdown.selectByIndex(1);
Reading the Currently Selected Option
categoryDropdown.selectByVisibleText("Dessert");
WebElement selectedOption = categoryDropdown.getFirstSelectedOption();
System.out.println("Currently selected: " + selectedOption.getText());
// If the dropdown allows multiple selections, use getAllSelectedOptions() instead
List<WebElement> selectedOptions = categoryDropdown.getAllSelectedOptions();
Full Example: Category Selection in Add Recipe
driver.findElement(By.id("recipeTitle")).sendKeys("Paneer Butter Masala");
Select categoryDropdown = new Select(driver.findElement(By.id("categoryDropdown")));
categoryDropdown.selectByVisibleText("Main Course");
System.out.println("Category set to: " + categoryDropdown.getFirstSelectedOption().getText());
driver.findElement(By.id("saveRecipeBtn")).click();
Custom (Non-<select>) Dropdowns
// A hypothetical custom JS dropdown, not a real <select>
driver.findElement(By.id("customCategoryDropdown")).click();
driver.findElement(By.xpath("//li[text()='Main Course']")).click();