Introduction
We use select by value, visible text, or index to pick an option from a dropdown menu in a web page automatically.
Select select = new Select(dropdown); select.selectByValue("value"); select.selectByVisibleText("text"); select.selectByIndex(index);
select.selectByValue("NY");select.selectByVisibleText("New York");select.selectByIndex(2);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 DropdownExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://example.com/dropdown"); WebElement dropdown = driver.findElement(By.id("state")); Select select = new Select(dropdown); select.selectByValue("CA"); System.out.println("Selected by value: CA"); select.selectByVisibleText("New York"); System.out.println("Selected by visible text: New York"); select.selectByIndex(3); System.out.println("Selected by index: 3"); driver.quit(); } }
Select class allows you to select an option from a dropdown by the exact text shown to the user?Select class provides methods to select dropdown options by different criteria: visible text, value attribute, or index.selectByVisibleText(String text) selects the option matching the exact text shown to the user.Select class?Select starts at 0, so the third option has index 2.selectByIndex(2) selects the third option correctly.<select id="colors"> <option value="r">Red</option> <option value="g">Green</option> <option value="b">Blue</option> </select>
Select select = new Select(driver.findElement(By.id("colors")));
select.selectByValue("g");Green.selectByValue("g") selects the option whose value attribute matches "g" exactly.Select select = new Select(driver.findElement(By.id("dropdown")));
select.selectByIndex(5);selectByIndex(5) throws NoSuchElementException because the index is out of range.<option value="1">Apple</option> <option value="2">Banana</option> <option value="3">Cherry</option> <option value="4">Date</option>
selectByIndex(2) selects the third option (index starts at 0).selectByValue("3") selects option with value "3".selectByVisibleText("Cherry") selects option with visible text "Cherry".Pass the test and this pattern moves unknown