Skip to content
CodeKruPro

Read the Employee Table Headers

70/80

Read the Employee Table Headers

A table header row is the th cells inside #employeeTable thead.

Task:

  1. Open Tables
  2. Read the four header cells
  3. Print them in order

Print the lines below exactly.

Expected output:

Header 1: Name
Header 2: Age
Header 3: Department
Header 4: Salary

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

  1. Find all header cells of the employee table. They live in its thead section.
  2. Loop over the resulting list with enumerate, and start the count at 1.
  3. Build each line from a label, the number as text, a colon and the cell's text.
  4. Print one line per header, in the order the columns appear on the page.

Common mistakes

  • Searching the whole page

    A plain search for th cells reads the second table too, so extra headers appear.

  • Adding an int to a string

    Without str() on the loop counter, the join fails with TypeError with the message can 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.

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.

main.py
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()