We use findElement by partialLinkText to find a link on a webpage when we only know part of its text. This helps us click or check links easily without needing the full text.
0
0
findElement by partialLinkText in Selenium Java
Introduction
When the full link text is long or changes but part of it stays the same.
When you want to click a link but only remember a few words from it.
When testing a webpage with many links that share similar text.
When the link text is dynamic but contains a fixed keyword.
When you want to avoid errors from exact text mismatches in links.
Syntax
Selenium Java
WebElement element = driver.findElement(By.partialLinkText("partial text"));The partialLinkText locator finds the first link containing the given text.
This method works only for links (<a> tags) on the page.
Examples
This finds the first link that has the word "Learn" anywhere in its text.
Selenium Java
WebElement element = driver.findElement(By.partialLinkText("Learn"));This finds a link with text containing "Contact", like "Contact Us" or "Contact Support".
Selenium Java
WebElement element = driver.findElement(By.partialLinkText("Contact"));This finds a link with "Home" in its text, such as "Homepage" or "Go Home".
Selenium Java
WebElement element = driver.findElement(By.partialLinkText("Home"));Sample Program
This program opens a browser, goes to example.com, finds a link with the word "More" in its text, prints the link text, clicks it, and then closes the browser.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class PartialLinkTextExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); // Find link containing 'More' in its text WebElement link = driver.findElement(By.partialLinkText("More")); System.out.println("Link text found: " + link.getText()); // Click the link link.click(); System.out.println("Clicked the link successfully."); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
If multiple links contain the partial text, only the first one is found.
Partial link text matching is case-sensitive in Selenium Java.
Make sure the link is visible and enabled before clicking it to avoid errors.
Summary
findElement by partialLinkText helps find links using part of their text.
It is useful when full link text is unknown or changes.
Remember it finds only the first matching link on the page.