</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How to locate a link using its text in Selenium?

Use By.linkText() for exact anchor text match and By.partialLinkText() for partial text match to locate hyperlinks.

Answer

Selenium provides two dedicated locators for anchor (<a>) elements:

1. By.linkText() — Exact match Matches the complete visible text of the link.

Java
WebElement link = driver.findElement(By.linkText("pavantestingtools"));
link.click();

2. By.partialLinkText() — Partial match Matches a substring of the link''s visible text.

Java
WebElement link = driver.findElement(By.partialLinkText("testingtools"));
link.click();

Comparison:

LocatorMatchesExample
linkTextExact full text"Click Here to Register"
partialLinkTextAny substring"Register"

When to use which:

  • Use linkText when the link text is unique and never changes
  • Use partialLinkText when the link text is long or partially dynamic (e.g., "Download Report 2025-06")

With Explicit Wait (recommended):

Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement link = wait.until(
    ExpectedConditions.elementToBeClickable(By.partialLinkText("Register"))
);
link.click();

Note: Both locators are case-sensitive and match only visible text, not the href attribute.

Follow AutomateQA

Related Topics