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
- Search the page for an element with the tag
h2using the tag strategy. - Keep the element in a variable.
- Read its visible text from the property made for that.
- Print the label
Heading:, a space, and the text.
Common mistakes
Writing the tag with angle brackets
Searching for
<h2>raisesNoSuchElementException, because Selenium looks for a tag with that exact odd name. Passh2alone.Calling text as a function
The line
heading.text()raisesTypeError: '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")returnsNone, and joining that to a label raisesTypeError. 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.
Related lessons
- Read Visible TextReads the visible text of several elements on another page.
- Find Every Radio ButtonUses the list form of the search to count many matches at once.
- Match a Link with By.LINK_TEXTMoves on to links and matches them by the words they show.
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/TextFields")
# Print the first h2 text as "Heading: ..."
finally:
driver.quit()