πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 45 of 100
Data Handling
Intermediate

Extracting All Rows and Cells from a Web Table

πŸ“ŠScenario Overview

Extracting All Rows and Cells from a Web Table

Key Takeaways & Cheat Sheet

  • βœ“Locate the table element and isolate header/body tags
  • βœ“Fetch all row elements using tbody/tr XPath locators
  • βœ“Iterate row lists and query cell values using td tags
  • βœ“Store cell values in lists of maps for clean assertion comparisons

Short Direct Answer

To extract web table content, locate the table body rows using `findElements`. Loop through the rows, and for each row, call `row.findElements(By.tagName("td"))` to extract its cell values. This ensures data is grouped logically by row.

⚠️ Senior Warning (Red Flag)

Never perform driver.findElement inside a nested loop without targeting the active row. If you query By.xpath("//td"), you will always extract the first cell of the entire table instead of the current row cell.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Always use tag names or dot-relative XPaths ("./td") when querying cells within a row WebElement to prevent Selenium from resetting the search scope back to the top of the HTML document.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Locate table row element handles
List<WebElement> rows = driver.findElements(By.xpath("//table[@id='users-tbl']/tbody/tr"));

for (WebElement row : rows) {
    // Locate cells relative to the current row element ONLY (use dot xpath prefix or tag name)
    List<WebElement> cells = row.findElements(By.tagName("td"));
    
    String name = cells.get(0).getText();
    String email = cells.get(1).getText();
    String status = cells.get(2).getText();
    
    System.out.println("Row Data: " + name + " | " + email + " | " + status);
}