About this lesson
Read table headers in Selenium Java with findElements(By.tagName("th"))
Learn Selenium JavaAdvancedTables
How it works
HTML tables put column titles in th cells, usually inside a thead, and data in td cells inside a tbody. Reading the headers first tells a test which column is which, so it can look up columns by name instead of by a fixed position.
Search inside the table, not the whole page. The Tables page has two tables, employeeTable and dynamicTable, and seven th cells between them. Calling findElements() on the table element returns only that table's four.
The list comes back in document order, left to right, so the position in the list is the column's position. That makes it easy to build a map from header text to column index.
About the assignment
The starter finds the employee table. You collect its header cells and print each one with a running number, so the output shows both the names and the order of the columns.
What you will do
- Call
findElements()on the table withBy.tagName("th"). - Loop over the list with an index.
- For each header, print the label
Header, the position counted from 1, a colon and the header's text, as the expected output shows.
Common mistakes
Searching from the driver
driver.findElements(By.tagName("th"))also returns the headers of the second table, and the output gets extra lines.Printing the zero-based index
List positions start at 0, the labels start at 1. Add one when printing.
Looking for td in the header row
Header cells are
th, so a search fortdin thetheadreturns an empty list.
In a real test suite
Table tests often start by checking the header row against the specification, then use the header positions to read the right column from each data row, which keeps them working if a column is added.
Lesson 63 captured elements. Lesson 65 reads single data cells by their ids.
Related lessons
- Count Table Rows and ColumnsCount rows and columns in the same table.
- Find Element by Tag Name
By.tagName(), the locator these lessons rely on. - Find Multiple Elements with findElements()How
findElements()lists work.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Tables");
WebElement table = driver.findElement(By.id("employeeTable"));
// TODO: Find all th elements in the table
// TODO: Print each header text
driver.quit();
}
}