How to select a dropdown value in Selenium WebDriver using Java

testing picture testing · Nov 22, 2013 · Viewed 420.7k times · Source

I am new to selenium , currently am working on selenium webdriver i want to select a value from the drop down. The id=periodId and the option is many in that am trying to select Last 52 weeks.

Here is the HTML code:

<select id="periodId" name="period" style="display: none;">
    <option value="l4w">Last 4 Weeks</option>
    <option value="l52w">Last 52 Weeks</option>
    <option value="daterange">Date Range</option>
    <option value="weekrange">Week Range</option>
    <option selected="" value="monthrange">Month Range</option>
    <option value="yeartodate">Year To Date</option>
</select>

Please suggest me some ways to click the drop down.

I tried with the above example lines but am getting error such as Element is not currently visible and so may not be interacted with Command duration or timeout: 32 milliseconds the drop downs values are the jquery multiselect widget format.

Answer

Abhishek Singh picture Abhishek Singh · Nov 22, 2013

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");