Selenium WebDriver and DropDown Boxes

2019-01-06 10:46发布

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?

10条回答
贼婆χ
2楼-- · 2019-01-06 11:27

For some strange reason the SelectElement for webdriver (version 2.25.1.0) does not properly work with the firefoxdriver (Firefox 15). Sometimes it may not select an option from a dropdownlist. It does, however, seem to work with the chromedriver... This is a link to the chromedriver... just drop it in the bin dir.

查看更多
闹够了就滚
3楼-- · 2019-01-06 11:27

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

Happy Coding :)

查看更多
Viruses.
4楼-- · 2019-01-06 11:28

Try the following:

import org.openqa.selenium.support.ui.Select;

Select droplist = new Select(driver.findElement(By.Id("selection")));   
droplist.selectByVisibleText("Germany");
查看更多
我命由我不由天
5楼-- · 2019-01-06 11:29

You can use this

(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");
查看更多
登录 后发表回答