How to use select list in selenium?


We can select an option from the dropdown list with Selenium webdriver. The Select class is used to handle static dropdown. A dropdown is identified with the <select> tag in an html code.

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

We have to import org.openqa.selenium.support.ui.Select to work with methods under Select class in our code. Let us see some of the Select methods−

  • selectByVisibleText(arg) – An option is selected if the text visible on the dropdown is the same as the parameter arg passed as an argument to the method.

    Syntax

    sel = Select (driver.findElement(By.id ("option")));

    sel.selectByVisibleText ("Selenium");

  • selectByValue(arg) – An option is selected if the value on the dropdown which is the same as the parameter arg passed as an argument to the method.

    Syntax

    sel = Select (driver.findElement(By.id("option")));

    sel.selectByValue ("val");

  • selectByIndex(arg) – An option is selected if the index on the dropdown which is the same as the parameter arg passed as an argument to the method. The index starts from 0.

    Syntax

    sel = Select (driver.findElement(By.id("option")));

    sel.selectByIndex(3);

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 SelectItem{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement p=driver.findElement(By.xpath("//[@name='continents']"));
      //Select class
      Select sel= new Select(p);
      // select with text visible
      sel.selectByVisibleText("Africa");
      // select with index
      sel.selectByIndex(5);
      driver.quit();
   }
}

Updated on: 18-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements