Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver w/Java: locating elements with multiple class names with one command

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.

like image 822
Will R. Avatar asked Apr 18 '13 17:04

Will R.


1 Answers

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.

like image 156
JimEvans Avatar answered Sep 28 '22 08:09

JimEvans