0

I am trying to grab a column from a data table. Here is my table to use as an example, what I am looking for is to extract the Firstname from the table.

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td class="abc">Jill</td>
    <td class="abc">Smith</td> 
    <td class="abc">50</td>
  </tr>
  <tr>
    <td class="abc">Eve</td>
    <td class="abc">Jackson</td> 
    <td class="abc">94</td>
  </tr>
</table>

How can i modify the code below to give me this result:

Jill
Eve 


WebElement table = driver.findElement(By.id("searchResultsGrid"));

// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
    List<WebElement> cells = row.findElements(By.tagName("td"));
    for (WebElement cell : cells) {
        System.out.println("content >>   " + cell.getText());
    }
}

1 Answer 1

2

Using Java 8 you can iterate list using .forEach after getting only Firstname column list as below :-

WebElement table = driver.findElement(By.id("searchResultsGrid"));

List<WebElement> firstCells = table.findElements(By.xpath(".//tr/td[1]"));
firstCells.forEach(firstCell->System.out.println("Firstname >>   " + firstCell.getText()));
Sign up to request clarification or add additional context in comments.

1 Comment

I had div ID that I used to get to the table I want, class is bad practice to use and I took it from there. I start reading about how to build custom xpath which made my life a lot easier. Thanks for your input as always.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.