</>

Technology

Scenario-Based

Difficulty

Intermediate

Interview Question

How do you test a table where data changes frequently in Selenium?

Answer

Testing Dynamic Tables in Selenium

Dynamic tables change rows, order, and content based on filters or live data. Never hardcode row numbers — use flexible locators.

Get All Rows and Columns

Java
// Get all rows in tbody
List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));
System.out.println("Total rows: " + rows.size());

// Iterate each row and get columns
for (WebElement row : rows) {
    List<WebElement> cols = row.findElements(By.tagName("td"));
    System.out.println("Name: " + cols.get(0).getText());
    System.out.println("Status: " + cols.get(2).getText());
}

Find a Row by Column Value

Java
// XPath: find row where first column is "John"
WebElement targetRow = driver.findElement(
    By.xpath("//table/tbody/tr[td[1][text()='John']]")
);

// Get another column from that same row
String status = targetRow.findElement(By.xpath("td[3]")).getText();
System.out.println("John's status: " + status);

Validate Specific Column in All Rows

Java
// Validate all "Status" column values are "Active"
List<WebElement> statusCells = driver.findElements(
    By.xpath("//table/tbody/tr/td[3]")
);
for (WebElement cell : statusCells) {
    Assert.assertEquals(cell.getText(), "Active",
        "Row has unexpected status: " + cell.getText());
}

Validate Table Sorting

Java
List<WebElement> nameCells = driver.findElements(
    By.xpath("//table/tbody/tr/td[1]")
);
List<String> actual  = nameCells.stream().map(WebElement::getText).collect(toList());
List<String> sorted  = new ArrayList<>(actual);
Collections.sort(sorted);
Assert.assertEquals(actual, sorted, "Table is not sorted alphabetically");

Handle Pagination

Java
while (true) {
    // Process current page rows
    List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));
    for (WebElement row : rows) {
        // validate or extract data
    }

    // Check if Next button is enabled
    WebElement nextBtn = driver.findElement(By.cssSelector(".pagination-next"));
    if (nextBtn.getAttribute("class").contains("disabled")) break;
    nextBtn.click();
    Thread.sleep(1000); // or use explicit wait
}

Best Practices

  • Validate only critical columns — not all data (avoid brittle tests)
  • Take a screenshot when a mismatch is found as evidence
  • Use XPath td[position()] instead of hardcoded column index where possible
  • For live data, validate structure/format rather than exact values

Follow AutomateQA

Related Topics