How to select an option from a dropdown menu using Selenium WebDriver and Java?

How to select an option from a dropdown menu using Selenium WebDriver and Java?

Using Select class with Visible Text: This solution utilizes the Select class provided by Selenium WebDriver to interact with dropdown elements. It locates the dropdown element by its ID, creates a Select object, and then selects the desired option by its visible text. This approach is straightforward and commonly used when you know the visible text of the option you want to select.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

// Assuming 'driver' is an instance of WebDriver

// Locate the dropdown element
WebElement dropdownElement = driver.findElement(By.id("yourDropdownId"));

// Create a Select object
Select dropdown = new Select(dropdownElement);

// Select option by visible text
dropdown.selectByVisibleText("Option Text");

Using Select class with Value: This solution selects an option from the dropdown by its value attribute. Each option in a dropdown may have a corresponding value attribute, which can be used to uniquely identify the option. This approach is beneficial when the value attribute is stable and reliable for selecting options, even if the visible text changes.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

// Assuming 'driver' is an instance of WebDriver

// Locate the dropdown element
WebElement dropdownElement = driver.findElement(By.id("yourDropdownId"));

// Create a Select object
Select dropdown = new Select(dropdownElement);

// Select option by value attribute
dropdown.selectByValue("optionValue");

Using Select class with Index: This solution selects an option from the dropdown by its index. Indexing starts from 0, so selectByIndex(2) will select the third option in the dropdown. This approach is useful when you know the position of the option you want to select, regardless of its visible text.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

// Assuming 'driver' is an instance of WebDriver

// Locate the dropdown element
WebElement dropdownElement = driver.findElement(By.id("yourDropdownId"));

// Create a Select object
Select dropdown = new Select(dropdownElement);

// Select option by index (0-based)
dropdown.selectByIndex(2);