如何获取列表中的所有项目

时间:2015-01-20 20:02:54

标签: java selenium selenium-webdriver

我需要获取列表中的所有项目,但我的脚本仅显示第一项。请参阅for循环中的verifyDisplay断言,我想在列表中显示所有项目。谢谢你的帮助。

我的剧本:

List<WebElement> groups = driver.findElements(By
            .xpath(".//*[@id='competitiveCategoryTemp']/option"));

    verifyDisplay("'" + competitive_categories_id_with_space + "'" + "===> The newly added Competitive Category is listed",
            By.xpath(".//*[@id='competitiveCategoryTemp']/option"));


    boolean sortedGroups = false;
    for (int i = 0; i < groups.size() - 1; i++) {

        verifyDisplay("'" + groups.get(i).getText() + "'" + "\n"+ 
                "Other Competitive Categories are available and names are SORTED",
                By.xpath(".//*[@id='competitiveCategoryTemp']/option"));

        if (groups.get(i).getText()
                .compareToIgnoreCase(groups.get(i + 1).getText()) > 0) {
            sortedGroups = true;
            break;

        }
        sortedGroups = true;
    }

    if (sortedGroups) {
        System.out.println("The Competitive Category names are SORTED");

    } else
        System.out.println("The Competitive Category names are UN-SORTED");

}

2 个答案:

答案 0 :(得分:1)

if (groups.get(i).getText()
            .compareToIgnoreCase(groups.get(i + 1).getText()) > 0) {
        sortedGroups = true;
        break;
}

如果满足此条件,则会跳出for循环,因此不会继续前进到第二个元素。这可能是问题吗?

答案 1 :(得分:1)

WebDriver有选择类来控制下拉对象。你的方法也会奏效。但是这样它看起来很整洁,你可以重用现有的方法。

导入此lib。

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

然后,

Select dropdown = new Select(driver.findElement(By.id("competitiveCategoryTemp")));

dropdown.getOptions()  // will return all the options - it is a List<WebElement>

//To use
for(WebElement option: dropdown.getOptions()){
   System.out.println(option.getText());
}

dropdown.getAllSelectedOptions() // will return the default selected options - it is a List<WebElement>