How to Select a Dropdown Value in Selenium Webdriver Using Java

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

Select from dropdown in selenium-webdriver javascript

In selenium-webdriver JavaScript you don't have "Select" class. You just need to simply click on drop-down option by passing correct css/xpath.

let element = driver.wait(until.elementLocated(By.css(cssLocator)));
element.click();

Selenium - How do I get the the list of options of a drop down list using java?

After clicking on the dropdown, you can get all the dropdown options in a list and later use them as you want(looping and selecting the desired option with specific condition or getting option by index).

  List<WebElement> options= driver.findElements(By.xpath("//span[@class='dropDown']/div/span"));
options.get(1).click(); // here 1 is the index value of the option to select or you can use loop if looking for some specific condition

For the image link you shared in the comment, try the following cssSelector:

List<WebElement> option= driver.findElements(By.cssSelector("div.questionDropdownOptions.activeSelectMenu span"));
option.get(1).click();
}

Note: Please import below packages in your code:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


Related Topics



Leave a reply



Submit