How to Find Element by Link Text in Selenium
In Selenium, you can find an element by its visible link text using
driver.find_element(By.LINK_TEXT, "link text"). This method locates the first anchor tag (<a>) with the exact text you provide.Syntax
The syntax to find an element by link text in Selenium is:
driver.find_element(By.LINK_TEXT, "link text"): Finds the first element with the exact visible link text.By.LINK_TEXT: Locator strategy to find links by their text."link text": The exact text shown on the link.
python
from selenium import webdriver from selenium.webdriver.common.by import By # Find element by exact link text element = driver.find_element(By.LINK_TEXT, "Example Link")
Example
This example opens a webpage and finds a link by its exact visible text, then prints the link's URL.
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 # Path to chromedriver executable (adjust path as needed) service = Service('/path/to/chromedriver') # Create WebDriver instance with webdriver.Chrome(service=service, options=options) as driver: driver.get('https://example.com') # Find link by exact text link = driver.find_element(By.LINK_TEXT, 'More information...') # Print the href attribute of the link print(link.get_attribute('href')) time.sleep(1) # Pause to see output if needed
Output
https://www.iana.org/domains/example
Common Pitfalls
Common mistakes when using find_element(By.LINK_TEXT, ...) include:
- Using partial or incorrect link text. The text must match exactly.
- Trying to find elements that are not anchor tags (
<a>). - Not waiting for the page or element to load before searching.
- Confusing
LINK_TEXTwithPARTIAL_LINK_TEXT, which allows partial matches.
Example of wrong and right usage:
python
from selenium.webdriver.common.by import By # Wrong: partial text with LINK_TEXT (raises NoSuchElementException) # driver.find_element(By.LINK_TEXT, 'More info') # Right: use PARTIAL_LINK_TEXT for partial matches # driver.find_element(By.PARTIAL_LINK_TEXT, 'More info')
Quick Reference
Summary of link text locators in Selenium:
| Locator | Description | Match Type |
|---|---|---|
| By.LINK_TEXT | Finds link by exact visible text | Exact match |
| By.PARTIAL_LINK_TEXT | Finds link containing given text | Partial match |
Key Takeaways
Use driver.find_element(By.LINK_TEXT, "text") to find links by exact visible text.
Link text must match exactly; use PARTIAL_LINK_TEXT for partial matches.
Only anchor tags () can be found by link text locators.
Wait for the page to load before searching for elements.
Incorrect text or locator causes NoSuchElementException.