Skip to main content
SeleniumDecoded
Back to Challenges

Find the Row by Its Content, Not Its Position

beginner Java 10 min

A test reads a user's status from row 3, column 4 of a table. Sorting changed and now it asserts on the wrong user. Locate the row by content.

The Scenario

The admin users table used to have three rows, sorted by name, and Ana Silva was always third. Then QA seeded a user called “Abby Lee”, the default sort moved to “last active”, and a “Team” column was added between Role and Status.

The test still passes some days. On others it asserts that Abel King is “Suspended” and fails, or reads the Team column and fails with a confusing message.

Your Task

Rewrite the lookup so it finds Ana’s row by a value that uniquely identifies her, and finds the Status cell by its column header. The test must keep working if rows are added, the sort order changes, or columns are reordered.

What Good Looks Like

  • No absolute XPath and no hard-coded row index.
  • The row is matched on a unique business value (email or user id), using normalize-space() so whitespace does not break it.
  • The column index is derived from the header text, with a clear error if the header is missing.
  • A wait on the row, because the table is populated by an API call after page load.

Your task

A test reads a user's status from row 3, column 4 of a table. Sorting changed and now it asserts on the wrong user. Locate the row by content.

Problem Code
// HTML under test (abridged):
// <table id="users">
//   <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th></tr></thead>
//   <tbody>
//     <tr><td>Aaron Wu</td><td>aaron@example.com</td><td>Editor</td><td>Active</td></tr>
//     <tr><td>Abel King</td><td>abel@example.com</td><td>Viewer</td><td>Invited</td></tr>
//     <tr><td>Ana Silva</td><td>ana@example.com</td><td>Admin</td><td>Suspended</td></tr>
//   </tbody>
// </table>

@Test
void suspendedUserShowsSuspended() {
    driver.get("https://app.example.com/admin/users");
    String status = driver.findElement(
        By.xpath("/html/body/main/table/tbody/tr[3]/td[4]")).getText();
    assertEquals("Suspended", status);
}

Need Help?

Solution

Try to solve the challenge yourself before revealing the solution.

Lessons that cover this