How to select a value from a static dropdown in Selenium?


The various methods available under Select class in Selenium to select a

value from a static dropdown. They are as listed below −

  • selectByVisibleText(String args)

    This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.

    Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>")));
    s.selectByVisibleText("Selenium");
  • selectByIndex(String args)

  • This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values.

  • Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>")));
    s.selectByIndex(1);
  • selectByValue(String args)

    This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.

    Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>")));
    s.selectByValue(“Testing”);

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 java.util.List;
import org.openqa.selenium.support.ui.Select;
public class SelectOptions{
   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/tutor_connect/index.php"; driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      Select s = new Select(driver.findElement(By.xpath("//select[@name=’selType’]")));
      // select an option by value method
      s.selectByValue("name");
      Thread.sleep(1000);
      // select an option by index method
      s.selectByIndex(0);
      Thread.sleep(1000);
      // select an option by visible text method
      s.selectByVisibleText("By Subject");
      Thread.sleep(1000);
      driver.quit();
   }
}

Updated on: 11-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements