Key takeaways
- linkText matches the full visible text; partialLinkText matches a substring.
- Both break on copy changes, so prefer a stable attribute when the text is likely to move.
- Whitespace and case matter, which is the usual reason a correct-looking locator fails.
Here is how to click a link by text with Selenium WebDriver in Java using the built in WebDriver helper methods or by XPath:
Click link by full text using Selenium WebDriver
WebElement linkByText = driver.findElement(By.linkText("My Link"));
linkByText.click();
Click link by partial text using Selenium WebDriver
WebElement linkByPartialText = driver.findElement(By.partialLinkText("First"))
linkByPartialText.click();
Click link by text using XPath in Selenium WebDriver
WebElement linkByTextUsingXPath = driver.findElement(By.xpath("//a[text()='First']"));
linkByTextUsingXPath.click();
Click link by partial text using XPath in Selenium WebDriver
WebElement linkByPartialTextUsingXPath = driver.findElement(By.xpath("//a[contains(text(),'ABC')]"));
linkByPartialTextUsingXPath.click();
More details here on how to locate elements with Selenium WebDriver.
LoadFocus is a cloud testing platform for:
- Load Testing
- Website Speed Testing
- Mobile Testing
- Automated Website Testing
- Visual Regression Testing
Frequently Asked Questions
What is the difference between linkText and partialLinkText?
linkText matches the full visible text of the anchor, partialLinkText matches any substring of it. Use the partial form when the label contains a value you cannot predict, such as a name or a count.
Why does my linkText locator not find the link?
Usually whitespace or case. The match is on the rendered text exactly as it appears, so a stray non breaking space, a line break in the markup or a CSS text-transform will all defeat a locator that looks correct.
Is locating by text a good idea?
It reads well, but it breaks whenever someone edits the copy, and it breaks in every localised build. Where the text is likely to move, prefer a stable id or a test attribute and keep text locators for content you are actually asserting on.