About this lesson
Selenium Python By.LINK_TEXT: find links by their exact text and read their ids
Selenium Python AssignmentsBeginnerLocators
How it works
Links are a tags, and a visitor sees them as clickable words. By.LINK_TEXT searches only a elements and compares the whole visible text of each one to your string. That makes it a natural way to find a link the way a person would, by reading its label.
The comparison is strict. A part of the label does not match, so searching for only the first words of a link raises NoSuchElementException. Letter case matters, and so does a trailing space.
You still need a second step to learn anything about the link. The element you get back has the usual members. get_attribute("id") returns the id as a string, and get_attribute("href") gives the full address the link points to. Keep each element in its own variable.
About the assignment
The Links page has several anchors. You pick out two of them by the exact words on screen and report the id attribute of each, which proves you reached the right ones.
What you will do
- Open the Links page. The starter has done this already.
- Find the link labelled with the first phrase from the task, using the link text strategy, and keep it in a variable.
- Find the link labelled with the second phrase and keep that in a second variable.
- Print each id on its own line, starting with the label
Link 1 ID:and thenLink 2 ID:.
Common mistakes
Passing only part of the label
A fragment such as the first two words raises
NoSuchElementException. This strategy needs the whole text, so use the partial strategy for fragments.Getting the case or spaces wrong
Lower-casing the label, or adding a space at the end, fails the same way. Copy the words as the page shows them.
Reusing one variable for both links
If both searches assign to the same name, the first element is lost before you read its id, and you print the same id twice.
In a real test suite
Link text is easy to read in a test, but it changes with translations and copy edits. Teams that test several languages often locate by an id or a data attribute and use the text only for an assertion.
The next lesson relaxes the rule and matches links from a fragment of their label.
Related lessons
- Match a Link with By.PARTIAL_LINK_TEXTMatches a link from just a fragment of its label.
- Locate a Field with By.IDFinds elements by id, the attribute you read here.
- Read an AttributeReads the value, name and type attributes of one field.
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/Links")
# Find the two links by their full text and print their ids
finally:
driver.quit()