Selenium WebDriver 和下拉框 [英] Selenium WebDriver and DropDown Boxes

查看:27
本文介绍了Selenium WebDriver 和下拉框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想选择下拉框的一个选项,有几种方法可以做到.我一直用:

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?

推荐答案

你可以试试这个:

IWebElement dropDownListBox = driver.findElement(By.Id("selection"));
SelectElement clickThis = new SelectElement(dropDownListBox);
clickThis.SelectByText("Germany");

这篇关于Selenium WebDriver 和下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆