带有Java的Selenium Webdriver:使用一个命令定位具有多个类名的元素 [英] Selenium Webdriver w/Java: locating elements with multiple class names with one command

查看:79
本文介绍了带有Java的Selenium Webdriver:使用一个命令定位具有多个类名的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Selenium (2.31.0, using JavaSE 1.6 and IE9) to find a series of elements on a page. These elements all have one of two class names, 'dataLabel' or 'dataLabelWide'. Currently, my code collects these elements in two separate ArrayLists, one for each class name, then converts them to arrays and combines them into one array. This method, however, lists the elements out of order, and I need them to be left in the same order as they're found in the page's HTML source.

我的代码的上述部分看起来像这样(添加了注释以供解释):

The above-mentioned section of my code looks like this (with comments added for explanation):

// 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.

我认为最有效的解决方案是找到具有类名的元素,以便它们被包括在内在一个列表/数组中立即。我自己做了一些搜索,但是我没有找到关于如何管理这项任务的任何结论性的想法。如果有办法做到这一点,请告诉我。

I think the most efficient solution would be to locate elements with either class name so they'd be included in a single list/array right away. I've done some searching on my own, but I haven't found any conclusive ideas on how I might manage this task. If there is some way to do this, please tell me about it.

推荐答案

为什么不做以下事情:

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

'。'选择器说,给我这个类的所有元素。','运算符是CSS选择器'或'运算符。

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

这篇关于带有Java的Selenium Webdriver:使用一个命令定位具有多个类名的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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