Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver and DropDown Boxes

If I want to select an option of a dropdown box, there are several ways to do that. I always used:

driver.findElement(By.id("selection")).sendKeys("Germany"); 

But that didn't work every time. Sometimes another option was selected. So I googled a little bit and found this piece of code which works every time:

WebElement select = driver.findElement(By.id("selection"));     List<WebElement> options = select.findElements(By.tagName("option"));     for (WebElement option : options) {         if("Germany".equals(option.getText()))             option.click();     } 

But that works really really slow. If I have a long list with many items in it, it really takes too much time. So my question is, is there a solution which works every time and is fast?

like image 278
tester Avatar asked Aug 29 '11 15:08

tester


People also ask

How do I select a value from a drop-down list in Selenium WebDriver without selection?

How will you select a particular value in a dropdown without using the methods of Select class in Selenium? We can select a particular value in a dropdown using the method of Select class by using findElements() method.

How many types of dropdowns are there in Selenium?

Different Types of Dropdowns, an Automation Test Engineer Must Know. In HTML, we encounter four types of dropdown implementations: Dropdown Navigation Options : These are usually encountered in NavBar of a website with dropdown links to other webpages.


2 Answers

You could try this:

IWebElement dropDownListBox = driver.findElement(By.Id("selection")); SelectElement clickThis = new SelectElement(dropDownListBox); clickThis.SelectByText("Germany"); 
like image 125
Michael Bautista Avatar answered Oct 16 '22 09:10

Michael Bautista


Try the following:

import org.openqa.selenium.support.ui.Select;  Select droplist = new Select(driver.findElement(By.Id("selection")));    droplist.selectByVisibleText("Germany"); 
like image 26
StatusQuo Avatar answered Oct 16 '22 08:10

StatusQuo