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:
| Locator | Matches | Example |
|---|---|---|
linkText | Exact full text | "Click Here to Register" |
partialLinkText | Any substring | "Register" |
When to use which:
- ✓Use
linkTextwhen the link text is unique and never changes - ✓Use
partialLinkTextwhen 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.
