About this lesson
Read table headers in Selenium Python with find_elements and enumerate
Selenium Python AssignmentsAdvancedTables
How it works
Header cells are th elements. To read several you use find_elements, which returns a Python list of WebElement objects in page order. A list lets you loop, count with len, and index with [0] or [-1].
Scope matters. The page holds two tables, and a tag-name search for th returned seven cells across both. Narrow it to the employeeTable id and its thead, which one CSS selector can express. A mistyped id makes find_elements return an empty list and raise nothing, while find_element raises NoSuchElementException. A silent empty loop often hides a typo.
For numbered lines use enumerate. It counts from zero by default, so pass start=1 to match how people count columns. Each th has a text property, already a clean string. The number is an int, so convert it with str() before joining.
About the assignment
You read the column titles of the employee table and print each with its position.
What you will do
- Find all header cells of the employee table. They live in its
theadsection. - Loop over the resulting list with
enumerate, and start the count at 1. - Build each line from a label, the number as text, a colon and the cell's
text. - Print one line per header, in the order the columns appear on the page.
Common mistakes
Searching the whole page
A plain search for
thcells reads the second table too, so extra headers appear.Adding an int to a string
Without
str()on the loop counter, the join fails withTypeErrorwith the messagecan only concatenate str (not "int") to str.Reaching past the end of the list
Asking for a fifth item raises
IndexError: list index out of range. Loop over the list instead.
In a real test suite
Page objects for table-heavy screens often expose a method returning the header texts as a list of strings, built with a list comprehension. A test compares it with the expected names, which catches a renamed or reordered column.
The next lessons read single cells, count rows and walk each row.
Related lessons
- Read Specific Cells from the Employee TableRead specific cells from the same employee table.
- Count Employee Rows and Columns with len()Count rows and columns of the table with
len(). - Find Every Radio ButtonAnother lesson built on
find_elementsreturning a list.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/Tables")
# Print the four employee table headers
finally:
driver.quit()