How to Select Value from DropDown using Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can select an option from the dropdown with its value attribute in Selenium webdriver by using the Select class. . A dropdown is represented by <select> tag and the options are represented by <option> tag.

To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.

Syntax

WebElement v = driver.findElement(By.name("selt"));
Select s = new Select(v);
s.selectByValue("val1");

Let us see the html code of a dropdown having value attribute for its options.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Select
public class SelectDrpDwn{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      //URL launch
      driver.get("http://www.uitestpractice.com/Students/Select");
      //identify dropdown
      WebElement n = driver.findElement(By.id("countriesSingle"));

      Select sl = new Select(n);
      //option by value
      sl.selectByValue("usa");
      //get option with text
      String s = sl.getFirstSelectedOption().getText();
      System.out.println("Value selected: : " + s);
      driver.quit();
   }
}

Output

raja
Published on 06-Apr-2021 14:23:39
Advertisements