Saturday, October 31, 2015

Locating elements using findElements methods





Selenium WebDriver provides the findElements() method, which returns List of WebElements with matching criteria. This method is useful when we want to do some operation with each element with same locator.

Examples

  • Get all links on a page
  • Get all buttons on page
  • Get all options from dropdown
  • Get all rows in table and td s from tr 

Let's create a test to check no of rows in given table.
@Test
public void testFindElements() {
  //Get all the tr from table
  List allTrs = driver.findElements(By.cssSelector("table[id='myContacts'] tr"));

  //verify there are 3 trs under given table
  assertEquals(3,allTrs.size());

  //Iterate all tr tags and print no of td tags in each tr tag
  for(WebElement eachTr : allTrs) {
    System.out.println(eachTr.findElements(By.tagName("td")).size());
  }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.