Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do WebDriver findElements retain the Table rows order on its retrieval

When retrieving an html table WebElement list such as the following (e.g. by tag):

webDriver.findElement(By.id("mainTable"))
         .findElements(By.tag("tr"))

Is there a guaranteed order for returned list? Can I safely assume element[i] comes before element[i+1] in the table rows order?

I've looked into the official docs, and googled around, but no luck.

like image 957
tomper Avatar asked Jul 05 '15 12:07

tomper


1 Answers

Yes, there is a guaranteed order for returned list and you can safely assume element[i] comes before element[i+1] in the table rows order.

You can refer the implementation of findElements() method in RemoteWebDriver and By class with different parameters. What you need is the below code for findElements method, which takes two string as parameters.

protected List<WebElement> findElements(String by, String using) {
  if (using == null) {
    throw new IllegalArgumentException("Cannot find elements when the selector is null.");
  }
  Response response = execute(DriverCommand.FIND_ELEMENTS,
      ImmutableMap.of("using", by, "value", using));
  Object value = response.getValue();
  List<WebElement> allElements;
  try {
    allElements = (List<WebElement>) value;
  } catch (ClassCastException ex) {
    throw new WebDriverException("Returned value cannot be converted to List<WebElement>: " + value, ex);
  }
  for (WebElement element : allElements) {
    setFoundBy(this, element, by, using);
  }
return allElements;
} 

Notice that the method uses ImmutableMap to return the web elements found and add them to a list.

An immutable, hash-based Map with reliable user-specified iteration order.

Since, ImmutableMap retains the iteration order, you can safely assume the WebElement list return by findElements method is ordered.

like image 102
Manu Avatar answered Oct 17 '22 12:10

Manu