0
0
Selenium Javatesting~5 mins

Select by value, visible text, index in Selenium Java

Choose your learning style9 modes available
Introduction
We use select by value, visible text, or index to pick an option from a dropdown menu in a web page automatically.
When you want to choose a country from a dropdown list on a signup form.
When you need to select a date from a dropdown calendar on a booking site.
When testing a website to make sure dropdown menus work correctly.
When automating repetitive tasks that involve selecting options from dropdowns.
Syntax
Selenium Java
Select select = new Select(dropdown);
select.selectByValue("value");
select.selectByVisibleText("text");
select.selectByIndex(index);
Use selectByValue when you know the option's value attribute.
Use selectByVisibleText when you want to select by the text shown to users.
Use selectByIndex when you want to select by the option's position starting at 0.
Examples
Selects the option whose value attribute is "NY".
Selenium Java
select.selectByValue("NY");
Selects the option that shows "New York" to the user.
Selenium Java
select.selectByVisibleText("New York");
Selects the third option in the dropdown (index starts at 0).
Selenium Java
select.selectByIndex(2);
Sample Program
This program opens a webpage with a dropdown menu for states. It selects options by value, visible text, and index, printing confirmation each time.
Selenium Java
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();
    }
}
OutputSuccess
Important Notes
Make sure the dropdown WebElement is found correctly before using Select.
Index starts at 0, so the first option is index 0.
Selecting by visible text is often easiest when you know exactly what the user sees.
Summary
Use Select class to interact with dropdown menus in Selenium Java.
You can select options by value, visible text, or index depending on what you know.
Always confirm the dropdown element is present before selecting.