如何使用selenium java验证元素/文本是否存在于下拉列表中

时间:2016-08-23 10:23:24

标签: selenium

如何使用selenium java

验证下拉列表中是否存在元素/文本
new Select(driver.findElement(By.id("airlineid"))).selectByVisibleText("Delta");

3 个答案:

答案 0 :(得分:1)

这可以通过使用Select类来完成。 要获得可见的选定选项:

WebElement select = driver.findElement(By.id("airlineid"));
WebElement option = select.getFirstSelectedOption();
String selectedValueInDropDown = option.getText();

获取所有选项:

Boolean found = false;
List<WebElement> allOptions = select.getOptions();
for(int i=0; i<allOptions.size(); i++) {
    if(alloptions[i].Equals("your_option_text")) {
        found=true;
        break;
    }
}
if(found) {
    System.out.println("Value exists");
}

答案 1 :(得分:0)

我不懂java,但我可以用c#给你代码,你可以根据java方法和编码标准进行修改

解决方法1

IWebElement dropDownElement = driver.FindElement(By.Id("continents"));
        if (dropDownElement.Text.Contains("the value you are looking for here"))
        {
            // value is present in drop down
        }
        else
        {
            // value is not present
        }

溶液2

IList<IWebElement> optionsofDropDown = driver.FindElements(By.XPath("//*[@id='continents']/option"));

foreach (IWebElement optionVal in optionsofDropDown)
{
   if (optionVal.Text == "the value you are looking for here")
   {
       //value available in drop down
        break;
    }
    else
    {
       //value available in drop down
    }
  }

答案 2 :(得分:0)

这对我有帮助:

Select select = new Select(select_drop_down);
List<WebElement> all_options = select.getOptions();
boolean found = false;

for (WebElement we : all_options) { 
    if (facility.equalsIgnoreCase(we.getAttribute("value"))) {
        select.selectByValue(facility);
        found = true;
        break;
    }
}