We can select the dropdown option in Selenium webdriver. The dropdowns can be worked upon with the help of the Select class. The select tag is used to represent a dropdown and option tag is used to represent items in the dropdown in html.
Let us investigate the html structure of a dropdown −
We have to add the statement − import org.openqa.selenium.support.ui.Select to use the Select class methods. The Select class methods are listed below −
selectByIndex(n) − An option is chosen based on the index of the option on the dropdown. The index n is passed as a parameter to the method. The index begins from 0.
Syntax −
Select s = Select (driver.findElement(By.name("select-dropdown"))); s.selectByIndex(0);
selectByValue(n) − An option is chosen based on the value of the option on the dropdown. The value n is passed as a parameter to the method.
Syntax −
Select s = Select (driver.findElement(By.name ("select-dropdown"))); s.selectByValue("value");
selectByVisibleText(n) − An option is chosen based on the text visible on the dropdown. The visible text n is passed as a parameter to the method.
Syntax −
Select s = Select (driver.findElement(By.name ("select-dropdown"))); s.selectByValue("text");
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.Select public class DropDownSelect{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); String url = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"; driver.get(url); // identify element WebElement m=driver .findElement(By.xpath("//*[@name='continents']")); //Select class for dropdown Select s = new Select(m); // select with text visible s.selectByVisibleText("Australia"); // select with index s.selectByIndex(2); driver.close(); } }