We use link text to find a clickable link on a webpage by its visible text. This helps us interact with links easily during testing.
0
0
Find element by link text in Selenium Python
Introduction
You want to click a link that has a unique visible text.
You need to verify if a specific link is present on the page.
You want to check the behavior after clicking a link with known text.
You want to automate navigation by clicking links with exact text.
Syntax
Selenium Python
element = driver.find_element(By.LINK_TEXT, "link text here")Use the exact visible text of the link inside the quotes.
Make sure to import By from selenium.webdriver.common.by.
Examples
Finds the link with visible text 'Home'.
Selenium Python
element = driver.find_element(By.LINK_TEXT, "Home")Finds the link with visible text 'Contact Us'.
Selenium Python
element = driver.find_element(By.LINK_TEXT, "Contact Us")Sample Program
This script opens a webpage with links, finds a link by its visible text 'HTML Links', prints its URL, clicks it, waits for the page to load, then prints the new URL.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome driver options options = Options() options.add_argument('--headless') # Run browser in headless mode # Setup Chrome driver service (adjust path to chromedriver if needed) service = Service() driver = webdriver.Chrome(service=service, options=options) try: # Open example page with links driver.get('https://www.w3schools.com/html/html_links.asp') # Find link by exact visible text link = driver.find_element(By.LINK_TEXT, 'HTML Links') # Print the href attribute of the link print(link.get_attribute('href')) # Click the link link.click() # Wait a moment for page to load time.sleep(2) # Print current URL after click print(driver.current_url) finally: driver.quit()
OutputSuccess
Important Notes
Link text must match exactly, including spaces and case.
If multiple links have the same text, only the first is found.
Use By.PARTIAL_LINK_TEXT if you want to match part of the link text.
Summary
Find element by link text locates links using their visible text.
It is simple and useful for clicking or verifying links.
Exact text match is required for this method.