How to Find Elements by Link Text and Partial Link Text in Selenium
Use Selenium’s exact and partial link-text locators, handle duplicate matches, and choose a stable locator for the page you are automating.
Selenium’s LINK_TEXT locator finds an anchor by its full visible text. PARTIAL_LINK_TEXT finds an anchor whose visible text contains the supplied phrase. In Python, use them with driver.find_element:
from selenium.webdriver.common.by import By
exact_link = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
partial_link = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
Both strategies locate links only; they do not locate buttons, headings, or arbitrary elements. If the label is stable, exact text is usually more specific. If only a reliable fragment is known, partial text can help, but check for duplicates before clicking. See Selenium’s locator strategies documentation.
1. Find a link by its exact visible text
Use By.LINK_TEXT when the complete visible link label is known and sufficiently stable:
from selenium.webdriver.common.by import By
link = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
print(link.get_attribute("href"))
The text argument is the link’s visible text, not its destination URL or an arbitrary HTML attribute. For example, if the page contains <a href="https://www.selenium.dev/">Selenium Official Page</a>, the locator uses Selenium Official Page.
Exact matching is useful when a page has links with similar labels and the full wording does not change. If the site changes punctuation, capitalization, localization, or wording, the locator may no longer identify the expected link. Treat link labels as page content that can change.
2. Find a link by partial visible text
Use By.PARTIAL_LINK_TEXT when a known fragment appears in the link label but the full wording varies:
from selenium.webdriver.common.by import By
link = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
print(link.get_attribute("href"))
The locator matches a link whose visible text contains the supplied string. A short fragment is more likely to match multiple links, so use a distinctive phrase when possible and inspect the matches before interacting.
3. Runnable Python example
This example opens a page, tries an exact link label, falls back to a partial phrase only if the exact label is absent, checks for ambiguity, and prints the selected link’s destination. Install Selenium and configure a browser driver for your environment before running it. The example uses Selenium’s Selenium Manager support for driver setup where available; consult the official Selenium Manager documentation for setup details.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
URL = "https://www.selenium.dev/"
EXACT_TEXT = "Downloads"
PARTIAL_TEXT = "Download"
driver = webdriver.Chrome()
try:
driver.get(URL)
matches = driver.find_elements(By.LINK_TEXT, EXACT_TEXT)
if not matches:
matches = driver.find_elements(By.PARTIAL_LINK_TEXT, PARTIAL_TEXT)
if not matches:
raise NoSuchElementException(
f"No link found for exact text {EXACT_TEXT!r} "
f"or partial text {PARTIAL_TEXT!r}"
)
if len(matches) > 1:
labels = [element.text for element in matches]
raise RuntimeError(f"Locator is ambiguous; matching labels: {labels!r}")
link = matches[0]
print("Visible label:", link.text)
print("Destination:", link.get_attribute("href"))
finally:
driver.quit()
Replace the URL and labels with values from your page. This checks whether the locator is unique in the current search context; it does not guarantee that the destination or page behavior is correct. Add assertions for the expected destination or outcome in your own test.
4. Handle duplicates and choose a locator
find_element returns the first matching element in its search context. If several links match, it does not report ambiguity for you. A broad partial phrase can therefore select a different link than intended. Use find_elements to collect all matches, inspect their text or attributes, and narrow the locator before clicking.
| Strategy | Use it when | Tradeoff |
|---|---|---|
By.LINK_TEXT |
The complete visible label is known and stable. | Wording changes can break the locator; applies only to links. |
By.PARTIAL_LINK_TEXT |
A distinctive part of a link label is reliable. | Short or common fragments can match several links; applies only to links. |
By.ID |
A unique, predictable ID is available. | An ID that changes between page loads or deployments is not a stable choice. |
By.CSS_SELECTOR |
A concise selector can identify the intended element or scope. | Long selectors tied to incidental page structure are harder to maintain. |
Selenium’s locator guidance recommends a unique, predictable ID when one is available; otherwise, use a well-written CSS selector. Keep locators compact and readable. Link text remains useful when the user-facing label is the clearest stable identifier. See Selenium’s tips on working with locators.
To narrow duplicate links, first identify a stable parent or section, then search within that element:
from selenium.webdriver.common.by import By
section = driver.find_element(By.ID, "resources")
links = section.find_elements(By.PARTIAL_LINK_TEXT, "Guide")
for link in links:
print(link.text, link.get_attribute("href"))
If a link label is duplicated inside the section too, choose a more specific stable ID or CSS selector, or validate the candidate’s attributes before acting. Avoid selecting by list position unless page order is itself part of the behavior under test.
5. Links only: buttons and other elements
Link-text strategies are specifically for anchor links. They are not general-purpose text searches. For a button, heading, or other element, use a suitable locator such as a stable ID or CSS selector. If the application exposes accessible roles and names, use the locator facilities available in your Selenium language binding and version; do not assume LINK_TEXT will find non-anchor elements.
When text is not a reliable identifier, prefer a unique predictable ID or a concise CSS selector. A locator based on text can also be inappropriate when the label is translated or intentionally changes by user state.
6. Other Selenium language bindings
The locator concepts are the same across Selenium bindings, but the APIs and syntax vary. Here are equivalent forms for common bindings; use the documentation for the binding and version installed in your project.
Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
WebElement exact = driver.findElement(By.linkText("Selenium Official Page"));
WebElement partial = driver.findElement(By.partialLinkText("Official Page"));
JavaScript
const { By } = require('selenium-webdriver');
const exact = await driver.findElement(By.linkText('Selenium Official Page'));
const partial = await driver.findElement(By.partialLinkText('Official Page'));
C#
using OpenQA.Selenium;
IWebElement exact = driver.FindElement(By.LinkText("Selenium Official Page"));
IWebElement partial = driver.FindElement(By.PartialLinkText("Official Page"));
For Python, the constants are By.LINK_TEXT and By.PARTIAL_LINK_TEXT. The Python API documents these locator values on its By API page. Check the Selenium locator documentation for the syntax supported by your binding.
7. Wait for dynamic links
If the link is added after navigation, an immediate lookup may happen too early. Use an explicit wait for the expected condition rather than adding an arbitrary long sleep. The following Python example waits for an exact-text link to become clickable:
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
link = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, "Downloads"))
)
link.click()
Adjust the timeout to the application and test environment. A wait can address timing; it cannot fix a wrong locator, a link that never appears, or an element hidden behind another control. For a partial-text wait, substitute By.PARTIAL_LINK_TEXT and the fragment.
8. Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
NoSuchElementException |
No matching anchor exists in the current search context at lookup time, or the text differs from the assumed label. | Inspect the rendered page and exact visible label; verify the search context and use an explicit wait if content loads later. |
| The wrong link is selected | A partial phrase matches more than one link, and find_element returns the first match. |
Use find_elements, inspect labels and destinations, and narrow the search to a stable section or locator. |
| A button is not found | Link-text locators target links, not buttons. | Locate the button with its ID, CSS selector, or another strategy appropriate to the element. |
| Lookup fails after a page update | The visible wording, punctuation, or localization changed. | Update the expected label or use a stable unique ID or CSS selector where available. |
| Lookup succeeds but click fails | The element may not yet be clickable, may be obscured, or may no longer be attached after a rerender. | Wait for clickability, inspect overlays and page state, and locate the element again after a rerender. |
| Multiple links are found unexpectedly | The partial phrase is too broad or occurs in repeated navigation and page content. | Choose a more distinctive phrase or scope the lookup to the intended container. |
9. Performance, reliability, and maintenance
Choose a locator for correctness and maintainability, not an assumed speed advantage. The cited Selenium guidance does not provide benchmark figures for comparing these strategies. Keep the locator simple, make it specific enough to identify the intended link, and use explicit waits only where the page’s timing requires them.
For reliable tests, verify the selected element before a consequential action: check its text, destination, or containing section. When labels are dynamic or localized, use a stable application identifier if available. When a page rerenders, reacquire the element rather than relying on an old element reference.
10. Or skip the browser setup
If your task is to capture a page rather than interact with its links, ScreenshotNeo can return a screenshot or PDF from one API request. The full ScreenshotNeo API documentation lists its request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo accepts cookie and consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, and failed loads are never billed, and response headers report the page verdict and billing status. Its MCP server gives AI agents screenshot, page-info, and PDF capture tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free account and get 1,000 screenshots a month with no card.
11. FAQ
Does partial link text mean a regular expression?
No. It matches when the link’s visible text contains the supplied search string; it is not a regular-expression locator.
Should I use link text or partial link text?
Use exact link text when the full label is stable. Use a distinctive partial phrase when only part of the wording is dependable, and check whether it matches multiple links.
Can I use these locators to find a link by its URL?
No. They match visible link text. Use an appropriate attribute-based locator, such as a CSS selector, when the destination URL is the identifying property.
What does find_element do when several links match?
It returns the first match in the current search context. Use find_elements when you need to inspect or choose among all matches. Selenium documents this behavior in Finding web elements.


