Working with Web Tables
Read and iterate HTML tables in Selenium: find rows by cell text, map columns by header name, handle pagination, and verify sorting without brittle XPath.
Almost every business application has a table somewhere: orders, users, invoices, audit logs. Tables are also where locator quality falls apart fastest. The classic mistake is //table/tbody/tr[3]/td[5], a locator that encodes two facts nobody promised you: that the row you want is third, and that the column you want is fifth. Add a column, change the default sort, or seed one extra record and the test reads the wrong cell without failing loudly.
This lesson shows how to treat a table as data: locate rows by what they contain, resolve columns by header name, and keep the DOM access in one helper so the rest of the test reads like a spreadsheet lookup.
Anatomy of an HTML Table
A well-formed table looks like this:
<table id="orders"> <thead> <tr><th>Order</th><th>Customer</th><th>Status</th><th>Total</th><th></th></tr> </thead> <tbody> <tr data-order-id="1042"> <td>INV-1042</td><td>Ada Lovelace</td><td>Paid</td><td>$120.00</td> <td><button>View</button></td> </tr> ... </tbody></table>Many modern “tables” are not <table> elements at all. Data grids such as AG Grid, MUI DataGrid and TanStack-based components render div elements with ARIA roles: role="grid" or role="table", role="row", role="columnheader", role="gridcell"/role="cell". The techniques below work for both; you swap tr/td/th for the role selectors.
| Native element | ARIA equivalent | CSS for the ARIA version |
|---|---|---|
table | role="table" or role="grid" | [role='grid'] |
tr | role="row" | [role='row'] |
th | role="columnheader" | [role='columnheader'] |
td | role="cell" or role="gridcell" | [role='gridcell'] |
Note: Virtualised grids only render the rows (and sometimes columns) currently in the viewport. A row that exists in the data may not exist in the DOM until you scroll to it. If
findElementsreturns 20 rows for a 5,000-row dataset, that is why. Filter the grid through its UI instead of scrolling through thousands of rows.
Reading the Whole Table
The first building block is turning the table into a list of rows, each a list of cell texts. Scope every search to the table element so stray tr elements elsewhere on the page do not leak in.
WebElement table = driver.findElement(By.id("orders"));List<WebElement> rows = table.findElements(By.cssSelector("tbody tr"));
List<List<String>> data = new ArrayList<>();for (WebElement row : rows) { List<String> cells = row.findElements(By.tagName("td")).stream() .map(WebElement::getText) .map(String::trim) .toList(); data.add(cells);}table = driver.find_element(By.ID, "orders")rows = table.find_elements(By.CSS_SELECTOR, "tbody tr")
data = [ [cell.text.strip() for cell in row.find_elements(By.TAG_NAME, "td")] for row in rows]const table = await driver.findElement(By.id('orders'));const rows = await table.findElements(By.css('tbody tr'));
const data = [];for (const row of rows) {const cells = await row.findElements(By.css('td'));data.push(await Promise.all(cells.map(async (c) => (await c.getText()).trim())));}var table = driver.FindElement(By.Id("orders"));var rows = table.FindElements(By.CssSelector("tbody tr"));
var data = rows .Select(row => row.FindElements(By.TagName("td")) .Select(cell => cell.Text.Trim()) .ToList()) .ToList();This works, but it is slow on large tables: every getText() is a separate round trip to the browser. A 50-row, 8-column table is 400+ HTTP calls. When you only need to read (not click), pull the whole table out in one JavaScript call.
String script = "return Array.from(arguments[0].querySelectorAll('tbody tr'))" + " .map(r => Array.from(r.cells).map(c => c.innerText.trim()));";
@SuppressWarnings("unchecked")List<List<String>> data = (List<List<String>>) ((JavascriptExecutor) driver).executeScript(script, table);script = """return Array.from(arguments[0].querySelectorAll('tbody tr')).map(r => Array.from(r.cells).map(c => c.innerText.trim()));"""data = driver.execute_script(script, table)const data = await driver.executeScript("return Array.from(arguments[0].querySelectorAll('tbody tr'))" +" .map(r => Array.from(r.cells).map(c => c.innerText.trim()));",table);var script = "return Array.from(arguments[0].querySelectorAll('tbody tr'))" + " .map(r => Array.from(r.cells).map(c => c.innerText.trim()));";
var raw = (IReadOnlyCollection<object>)((IJavaScriptExecutor)driver).ExecuteScript(script, table);var data = raw .Select(r => ((IReadOnlyCollection<object>)r).Select(c => c.ToString()).ToList()) .ToList();innerText respects CSS visibility like getText() does, so hidden cells come back empty rather than leaking hidden text. Use the JavaScript approach for assertions over many rows; use WebElements when you need to interact with something inside a row.
Mapping Columns by Header Name
Hard-coded column indexes are the number one cause of silently wrong table assertions. Build a header map once per table and look columns up by name.
Map<String, Integer> columnIndex(WebElement table) { List<WebElement> headers = table.findElements(By.cssSelector("thead th")); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < headers.size(); i++) { String name = headers.get(i).getText().trim(); if (!name.isEmpty()) { map.put(name, i); } } return map;}
Map<String, Integer> cols = columnIndex(table);int statusCol = cols.get("Status"); // NullPointerException here = header renamed, which is what you want to knowdef column_index(table): headers = table.find_elements(By.CSS_SELECTOR, "thead th") return {h.text.strip(): i for i, h in enumerate(headers) if h.text.strip()}
cols = column_index(table)status_col = cols["Status"] # KeyError = header renamedasync function columnIndex(table) {const headers = await table.findElements(By.css('thead th'));const map = new Map();for (let i = 0; i < headers.length; i++) { const name = (await headers[i].getText()).trim(); if (name) map.set(name, i);}return map;}
const cols = await columnIndex(table);const statusCol = cols.get('Status');Dictionary<string, int> ColumnIndex(IWebElement table){ var headers = table.FindElements(By.CssSelector("thead th")); return headers .Select((h, i) => (Name: h.Text.Trim(), Index: i)) .Where(x => x.Name.Length > 0) .ToDictionary(x => x.Name, x => x.Index);}
var cols = ColumnIndex(table);var statusCol = cols["Status"];Two details that matter in real apps:
- Sort icons and tooltips in headers. A header might render as “Status ▲” or include hidden screen-reader text. Normalise: strip non-letters, or read a stable attribute such as
data-column="status"if the developers provide one. colspanin the header or body. If any header cell spans several columns, the visual index and the DOM index diverge. Either resolve indexes usingcellIndexon the body cells, or ask fordata-columnattributes on cells. Tables with merged cells are a good reason to have a conversation with the team that owns the component.
Finding a Row by Cell Text
The most common table operation is “find the row for order INV-1042 and do something in it”. There are two clean ways.
Option 1: XPath with a text predicate
XPath can select a row by the content of one of its cells, then you scope further searches to that row:
//table[@id='orders']//tbody/tr[td[normalize-space()='INV-1042']]Read it as: “the tr that has a td whose normalised text is INV-1042”. normalize-space() trims and collapses whitespace, which protects you from formatting differences. If you need to match a specific column, combine it with the header map:
//table[@id='orders']//tbody/tr[td[3][normalize-space()='Paid']]Here the 3 is generated from the header map (XPath is 1-based, so index + 1), not typed by hand.
Option 2: Filter rows in code
When the matching logic is more than exact text (case-insensitive, regex, multiple columns), filter in your language instead.
WebElement findRow(WebElement table, String column, String value) { int col = columnIndex(table).get(column); return table.findElements(By.cssSelector("tbody tr")).stream() .filter(row -> { List<WebElement> cells = row.findElements(By.tagName("td")); return cells.size() > col && cells.get(col).getText().trim().equals(value); }) .findFirst() .orElseThrow(() -> new NoSuchElementException( "No row where " + column + " = '" + value + "'"));}
WebElement row = findRow(table, "Order", "INV-1042");row.findElement(By.cssSelector("button")).click();def find_row(table, column, value): col = column_index(table)[column] for row in table.find_elements(By.CSS_SELECTOR, "tbody tr"): cells = row.find_elements(By.TAG_NAME, "td") if len(cells) > col and cells[col].text.strip() == value: return row raise NoSuchElementException(f"No row where {column} = '{value}'")
row = find_row(table, "Order", "INV-1042")row.find_element(By.CSS_SELECTOR, "button").click()async function findRow(table, column, value) {const col = (await columnIndex(table)).get(column);for (const row of await table.findElements(By.css('tbody tr'))) { const cells = await row.findElements(By.css('td')); if (cells.length > col && (await cells[col].getText()).trim() === value) { return row; }}throw new Error('No row where ' + column + " = '" + value + "'");}
const row = await findRow(table, 'Order', 'INV-1042');await row.findElement(By.css('button')).click();IWebElement FindRow(IWebElement table, string column, string value){ var col = ColumnIndex(table)[column]; return table.FindElements(By.CssSelector("tbody tr")) .FirstOrDefault(row => { var cells = row.FindElements(By.TagName("td")); return cells.Count > col && cells[col].Text.Trim() == value; }) ?? throw new NoSuchElementException($"No row where {column} = '{value}'");}
var row = FindRow(table, "Order", "INV-1042");row.FindElement(By.CssSelector("button")).Click();Tip: If rows carry a stable key such as
data-order-id="1042"ordata-row-key, skip all of this and usetr[data-order-id='1042']. A row key attribute is the single most valuable test hook you can ask a front-end team for on a table.
Once you have a row element, every subsequent findElement call should go through it (row.findElement(...)), not through driver. That scoping is what guarantees you click the View button in this row and not the first View button on the page.
Waiting for Table Data
Tables are usually filled by an API call after the page loads. Asserting on the table right after navigation either sees zero rows or a “Loading…” placeholder row. Wait for a real data condition, not for the table element (which often exists before the data does).
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(d -> d.findElements(By.cssSelector("#orders tbody tr[data-order-id]")).size() > 0);wait = WebDriverWait(driver, 10)wait.until(lambda d: len(d.find_elements(By.CSS_SELECTOR, "#orders tbody tr[data-order-id]")) > 0)await driver.wait(async () => {const rows = await driver.findElements(By.css('#orders tbody tr[data-order-id]'));return rows.length > 0;}, 10000);var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));wait.Until(d => d.FindElements(By.CssSelector("#orders tbody tr[data-order-id]")).Count > 0);Selecting tr[data-order-id] instead of plain tr excludes the empty-state and loading rows, which typically do not have the key attribute. If you are waiting for a table to change (after filtering, sorting, or paging), wait for the old first row to go stale or for the expected content to appear; see waiting for text to change.
Pagination
Paginated tables need a loop: read the current page, click Next, wait for the page to actually change, repeat until Next is disabled. The “wait for the page to change” step is the one people skip, and it is why paginated tests read page 1 twice.
List<List<String>> all = new ArrayList<>();WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
while (true) { WebElement table = driver.findElement(By.id("orders")); all.addAll(readRows(table)); // the single-round-trip reader from above
WebElement next = driver.findElement(By.cssSelector("[aria-label='Next page']")); if (!next.isEnabled() || "true".equals(next.getDomAttribute("aria-disabled"))) { break; } WebElement firstRow = table.findElement(By.cssSelector("tbody tr")); next.click(); wait.until(ExpectedConditions.stalenessOf(firstRow));}all_rows = []wait = WebDriverWait(driver, 10)
while True: table = driver.find_element(By.ID, "orders") all_rows.extend(read_rows(table))
nxt = driver.find_element(By.CSS_SELECTOR, "[aria-label='Next page']") if not nxt.is_enabled() or nxt.get_dom_attribute("aria-disabled") == "true": break first_row = table.find_element(By.CSS_SELECTOR, "tbody tr") nxt.click() wait.until(EC.staleness_of(first_row))const all = [];while (true) {const table = await driver.findElement(By.id('orders'));all.push(...(await readRows(table)));
const next = await driver.findElement(By.css("[aria-label='Next page']"));const disabled = !(await next.isEnabled()) || (await next.getAttribute('aria-disabled')) === 'true';if (disabled) break;
const firstRow = await table.findElement(By.css('tbody tr'));await next.click();await driver.wait(until.stalenessOf(firstRow), 10000);}var all = new List<List<string>>();var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
while (true){ var table = driver.FindElement(By.Id("orders")); all.AddRange(ReadRows(table));
var next = driver.FindElement(By.CssSelector("[aria-label='Next page']")); if (!next.Enabled || next.GetDomAttribute("aria-disabled") == "true") break;
var firstRow = table.FindElement(By.CssSelector("tbody tr")); next.Click(); wait.Until(d => { try { _ = firstRow.Displayed; return false; } catch (StaleElementReferenceException) { return true; } });}Staleness works when the framework re-renders the rows. Some frameworks reuse the same tr nodes and only swap their text, in which case the old row never goes stale and the wait times out. If that happens, wait on something that does change: the “Showing 21-40 of 312” label, the page number with aria-current="page", or the first row’s key attribute.
Warning: Do not walk through every page to find one record. Use the table’s search or filter box, or query the API directly, then assert on the single page that results. Paging through 30 pages to find a row turns a two-second test into a forty-second one and multiplies the flakiness surface.
Verifying Sorting
To test “clicking the Total header sorts descending”, read the column, then compare it against a sorted copy. Parse values into the right type first: string-sorting $1,200.00 and $95.00 gives the wrong order.
driver.findElement(By.xpath("//thead//th[normalize-space()='Total']")).click();wait.until(d -> "descending".equals( d.findElement(By.xpath("//thead//th[normalize-space()='Total']")).getDomAttribute("aria-sort")));
int col = columnIndex(table).get("Total");List<BigDecimal> totals = readRows(table).stream() .map(r -> new BigDecimal(r.get(col).replaceAll("[^0-9.\\-]", ""))) .toList();
List<BigDecimal> expected = new ArrayList<>(totals);expected.sort(Comparator.reverseOrder());assertEquals(expected, totals);header = driver.find_element(By.XPATH, "//thead//th[normalize-space()='Total']")header.click()wait.until(lambda d: d.find_element( By.XPATH, "//thead//th[normalize-space()='Total']").get_dom_attribute("aria-sort") == "descending")
col = column_index(table)["Total"]totals = [Decimal(re.sub(r"[^0-9.\-]", "", r[col])) for r in read_rows(table)]assert totals == sorted(totals, reverse=True)const totalHeader = By.xpath("//thead//th[normalize-space()='Total']");await driver.findElement(totalHeader).click();await driver.wait(async () =>(await driver.findElement(totalHeader).getAttribute('aria-sort')) === 'descending', 10000);
const col = (await columnIndex(table)).get('Total');const totals = (await readRows(table)).map((r) => parseFloat(r[col].replace(/[^0-9.-]/g, '')));const expected = [...totals].sort((a, b) => b - a);assert.deepStrictEqual(totals, expected);var totalHeader = By.XPath("//thead//th[normalize-space()='Total']");driver.FindElement(totalHeader).Click();wait.Until(d => d.FindElement(totalHeader).GetDomAttribute("aria-sort") == "descending");
var col = ColumnIndex(table)["Total"];var totals = ReadRows(table) .Select(r => decimal.Parse(Regex.Replace(r[col], @"[^0-9.\-]", ""), CultureInfo.InvariantCulture)) .ToList();CollectionAssert.AreEqual(totals.OrderByDescending(t => t).ToList(), totals);Notes on sort tests:
- Wait for the sort to apply.
aria-sorton the header is the most reliable signal for accessible tables. Otherwise, wait for the first row to change. - Sort a known dataset. If the table only has rows that happen to be in order already, the test passes even when sorting is broken. Seed data that is deliberately out of order.
- Locale matters for strings. Server-side sorting may use database collation (case-insensitive, accent-aware) while your language’s default sort is ordinal. Compare with a matching collator, or assert on a dataset that avoids ambiguous cases.
- Paginated sorting is server-side. Checking that page 1 is sorted does not prove page 2 continues the order. Check the last row of page 1 against the first row of page 2 if it matters.
Wrapping It Up as a Table Component
All of these helpers belong in one reusable class rather than scattered across page objects. A DataTable component that takes the table’s root element and exposes rows(), column(name), rowWhere(column, value) and sortBy(column) keeps the selectors in one place, and every page with a table reuses it. That pattern is covered in detail in Component Objects.
Common Pitfalls
| Symptom | Likely cause | Fix |
|---|---|---|
| Test reads the wrong cell after a release | Hard-coded column index | Resolve indexes from headers or data-column attributes |
| Zero rows found right after navigation | Data loads asynchronously | Wait for keyed data rows, not the table element |
| Same page read twice during pagination | No wait after clicking Next | Wait for staleness or for the page label to change |
| StaleElementReferenceException when clicking in a row | Table re-rendered between find and click | Re-find the row by key right before interacting |
| Only 20 rows of 5,000 found | Virtualised grid | Filter via the UI or verify via API |
| Numeric sort assertion fails on correct data | Comparing strings | Parse to numbers or dates before comparing |
| Very slow table assertions | One getText() call per cell | Read the table with a single executeScript |
Summary
- Locate rows by content or by a row key, never by position.
- Resolve columns by header name and fail loudly if a header disappears.
- Scope every search inside a row to that row element.
- Wait for real data rows, and wait for page changes during pagination.
- Parse values before asserting on sort order, and seed data that would expose a broken sort.
- Read large tables in one JavaScript round trip when you only need text.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.