java selenium webdriver从下拉菜单中选择按值忽略区分大小写

时间:2015-07-16 16:34:21

标签: java select drop-down-menu selenium-webdriver html-select

我无法通过使用SelectByValue忽略区分大小写来从下拉菜单中进行选择。

例如:                       日本         阿尔巴尼亚     

据了解,价值是日本。但是,我拥有的价值可以是“日本”或“日本”。

我可以通过使用来选择。但是,如果列表很大,则需要相当长的时间。

// get dropdown elements
Select dropdown = new Select(findElementHelper(by));
// get elements based on options from dropdown menu
List<WebElement> myElements = dropdown.getOptions(); //because of  listing takes time
// test until value of element and given value is equal
String tempValue = value.trim();
for (WebElement option : myElements) {
    if (tempValue.equalsIgnoreCase(option.getAttribute("value").trim())) {
        // tryClick(option,value) did not work on ie
        /*if (!tryClick(option,value)){
            System.out.println(value + " is not selected");
           return false;
       } option.click(); //worked one
        break;
    }
}

我尝试过使用正确输入的Select类,它的工作速度比我的代码快得多。是否有任何方法可以忽略selectByValue中的区分大小写。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

selectByValue()的Selenium实现使用xpath搜索给定值,而不是遍历所有选项。您应该能够将xpath搜索更改为将所有内容更改为小写。如果您知道只有一个具有给定值的选项,则可以通过删除List和for循环来进一步简化此选项。

WebElement dropdownElement = findElementHelper(by);

String tempValue = value.trim().toLowerCase();

List<WebElement> matchingValues = dropdownElement.findElements(By.xpath(
        ".//option[lower-case(@value) = '" + tempValue + "']"));    

for(WebElement matchingValue : matchingValues)
{
     /* Do what you want with the options         
     if (!option.isSelected()) {
         option.click();
     } */
}

我不能在Java中使用Selenium,因此我无法对此进行测试,但它应该非常接近。如果这更快,请告诉我。