Skip to content
CodeKruPro

Locate a Heading with By.TAG_NAME

7/80

Locate a Heading with By.TAG_NAME

By.TAG_NAME matches the HTML tag. find_element returns the first match. .text is the visible text.

Task:

  1. Find the first h2
  2. Print its visible text

Print the lines below exactly.

Expected output:

Heading: Text Fields

About this lesson

Selenium Python By.TAG_NAME: find the first h2 and read its visible text

Selenium Python AssignmentsBeginnerLocators

How it works

Every element on a page has a tag, such as h2, input or a. By.TAG_NAME finds elements by that tag and nothing else. A page almost always has many elements with the same tag, so this locator works best for tags that appear once or in a predictable order.

When more than one element has the tag, find_element returns the first in document order. This page has only one h2, but on any page find_element would give you the first, with no extra filter needed. find_elements would give you a list of all of them in order.

Once you hold the element, element.text returns the text a user can see, as a str. It is a property, so no parentheses. That differs from an attribute, so get_attribute("text") is the wrong tool and returns None.

About the assignment

You locate the main heading of the Text Fields page through its tag and read the words a visitor would see. The task calls it the first h2, so the plain single-element search is enough.

What you will do

  1. Search the page for an element with the tag h2 using the tag strategy.
  2. Keep the element in a variable.
  3. Read its visible text from the property made for that.
  4. Print the label Heading:, a space, and the text.

Common mistakes

  • Writing the tag with angle brackets

    Searching for <h2> raises NoSuchElementException, because Selenium looks for a tag with that exact odd name. Pass h2 alone.

  • Calling text as a function

    The line heading.text() raises TypeError: 'str' object is not callable. The property already holds the string.

  • Reading an attribute where text is wanted

    An attribute lookup such as get_attribute("text") returns None, and joining that to a label raises TypeError. Use the text property for words on screen.

In a real test suite

Tag lookups are common inside a located container. A test finds a table, then asks that element for its tr rows.

The next two lessons turn to links, which have two special strategies that match on the words inside the anchor.

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/TextFields")
    # Print the first h2 text as "Heading: ..."
finally:
    driver.quit()