9

我正在尝试使用 Selenium(2.31.0,使用 JavaSE 1.6 和 IE9)在页面上查找一系列元素。这些元素都有两个类名之一,“dataLabel”或“dataLabelWide”。目前,我的代码将这些元素收集在两个单独的 ArrayList 中,每个类名一个,然后将它们转换为数组并将它们组合成一个数组。但是,此方法会乱序列出元素,我需要将它们保留在与在页面的 HTML 源中找到的相同的顺序中。

我的代码的上述部分如下所示(添加了注释以进行解释):

// Application runs on WebDriver d, an InternetExplorerDriver.
// After navigating to the page in question...

List<WebElement> labels = d.findElements(By.className("dataLabel"));
List<WebElement> wLabels = d.findElements(By.className("dataLabelWide"));
// Locates the elements of either type by their respective class name.

WebElement[] labelsArray = labels.toArray(new WebElement[labels.size()]);
WebElement[] wLabelsArray = wLabels.toArray(new WebElement[wLabels.size()]);
// Converts each ArrayList to an array.

List<WebElement> allLabels = new ArrayList<WebElement>();
// Creates an ArrayList to hold all elements from both arrays.

for(int a = 0; a < labelsArray.length; a++) {
    allLabels.add(labelsArray[a]);
}
for(int b = 0; b < wLabelsArray.length; b++) {
    allLabels.add(wLabelsArray[b]);
}
// Adds elements of both arrays to unified ArrayList, one by one.

WebElement[] allLabelsArray = allLabels.toArray(new WebElement[allLabels.size()]);
// Finally converts unified ArrayList into array usable for test purposes.
// Far too complicated (obviously), and elements end up out-of-order in array.

我认为最有效的解决方案是使用任一类名定位元素,以便立即将它们包含在单个列表/数组中。我自己进行了一些搜索,但我还没有找到任何关于如何管理这项任务的结论性想法。如果有什么方法可以做到这一点,请告诉我。

4

1 回答 1

29

Why wouldn't you do the following:

driver.findElement(By.cssSelector(".dataLabel,.dataLabelWide");

The '.' selector says, "give me all elements with this class." The ',' operator is the CSS selector 'or' operator.

于 2013-04-18T18:06:41.830 回答