How to select an item from a dropdown list using Selenium WebDriver with java?



We can select an item from a dropdown list with Selenium webdriver. The Select class in Selenium is used to work with dropdown. In an html document, the dropdown is described with the <select> tag.

Let us consider the below html code for <select> tag.

For utilizing the methods of Select class we have to import org.openqa.selenium.support.ui.Select in our code. Let us see how to select an item with the Select methods−

  • selectByVisibleText(arg) – An item is selected based on the text visible on the dropdown which matches with parameter arg passed as an argument to the method.

    Syntax−

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByVisibleText ('Text');

  • selectByValue(arg) – An item is selected based on the value of the option on the dropdown which matches with parameter arg passed as an argument to the method.

    Syntax−

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByValue ('Val');

  • selectByIndex(arg) – An item is selected based on the index of the option on the dropdown which matches with parameter arg passed as an argument to the method. The index starts from 0.

    Syntax−

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByIndex (1);

Example

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 SelectDropDownItem{    public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");       WebDriver driver = new ChromeDriver();       String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"       driver.get(u);       driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);       // identify element       WebElement t=driver.findElement(By.xpath("//*[@name='continents']"));       //Select class for dropdown       Select select = new Select(t);       // select an item with text visible       select.selectByVisibleText("Australia");       // select an item with item index       select.selectByIndex(1);       driver.close();    } }
Updated on: 2020-09-18T09:26:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements