0
0
Selenium Pythontesting~5 mins

Find element by partial link text in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes you only know part of a link's text on a webpage. Finding elements by partial link text helps you click or check links without needing the full text.

When the full link text is long or dynamic but a unique part is stable.
When you want to click a link but only remember part of its text.
When testing websites with many similar links and you want to target a group by shared text.
When the link text changes slightly but contains a consistent keyword.
When automating navigation through menus with partial known labels.
Syntax
Selenium Python
element = driver.find_element(By.PARTIAL_LINK_TEXT, "partial_text")

Use By.PARTIAL_LINK_TEXT to find links containing the given text.

This works only for <a> tags with visible text.

Examples
Finds the first link containing the word "Learn" anywhere in its text.
Selenium Python
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Learn")
Finds a link with text like "Contact Us" or "Contact Support".
Selenium Python
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Contact")
Finds all links containing "Help" in their text.
Selenium Python
elements = driver.find_elements(By.PARTIAL_LINK_TEXT, "Help")
Sample Program

This script opens a webpage with links, finds a link containing "Try it" in its text, and prints the full text of that link. It uses headless Chrome to run without opening a browser window.

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

# Initialize driver (adjust path to chromedriver as 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 partial link text
    element = driver.find_element(By.PARTIAL_LINK_TEXT, 'Try it')

    # Print the full link text found
    print(f"Found link text: {element.text}")

finally:
    driver.quit()
OutputSuccess
Important Notes

Partial link text matching is case-sensitive in Selenium.

If multiple links match, find_element returns the first one found.

Use find_elements to get all matching links as a list.

Summary

Partial link text helps find links when you only know part of their text.

It works only on <a> elements with visible text.

Use it to make tests more flexible and less brittle.