Skip to main content

How to Click a Link by Text in Selenium WebDriver Java

How to Click a Link by Text in Selenium WebDriver Java

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:


WebElement linkByText = driver.findElement(By.linkText("My Link"));
linkByText.click();

WebElement linkByPartialText = driver.findElement(By.partialLinkText("First"))
linkByPartialText.click();

WebElement linkByTextUsingXPath = driver.findElement(By.xpath("//a[text()='First']"));
linkByTextUsingXPath.click();

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:

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.

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.

Chris

Head of Content at LoadFocus

Chris leads content and oversees development across the services this blog covers. The guides and tool comparisons here come out of the same decisions that shape what ships.

Weekly tips right in your inbox.

Don’t miss out on the latest testing tips and tricks, tools and news related to software testing.

Already +20,000 members in the list.

The Load Testing Platform with AI That Explains Your Results

Load test websites and APIs from 25 cloud regions, monitor page speed and uptime, and get AI analysis that explains your results in plain English.

Cloud load testing, website speed and API monitoring in one place.

Hi there! Can I share a cool thing I'm working on with you?

A software testing newsletter that sparks joy.

Our goal is to create helpful content for software developers and testers.

If you're not into it, you can unsubscribe instantly.