0
0
Selenium Javatesting~5 mins

findElement by linkText in Selenium Java

Choose your learning style9 modes available
Introduction

We use findElement by linkText to find a clickable link on a webpage by its exact visible text. This helps us interact with links easily during testing.

When you want to click a link with a known exact text, like 'Home' or 'Contact Us'.
When testing navigation by clicking on menu items that are links.
When verifying that a specific link is present on the page.
When automating form submissions that require clicking a link to proceed.
When you want a simple way to locate links without using complex selectors.
Syntax
Selenium Java
WebElement element = driver.findElement(By.linkText("exact link text"));

The text must match the link's visible text exactly, including spaces and case.

This method only works for <a> tags with visible text.

Examples
Finds the link with text exactly 'Home'.
Selenium Java
WebElement homeLink = driver.findElement(By.linkText("Home"));
Finds the link with text exactly 'Contact Us'.
Selenium Java
WebElement contactLink = driver.findElement(By.linkText("Contact Us"));
Finds a link with a non-breaking space as text (rare case).
Selenium Java
WebElement emptyLink = driver.findElement(By.linkText(" "));
Sample Program

This program opens a browser, goes to example.com, tries to find the link with text 'More information...'. It prints if the link is found and visible or not. If the link is missing, it prints 'Link not found.' Finally, it 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 LinkTextExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            WebElement moreInfoLink = driver.findElement(By.linkText("More information..."));
            if (moreInfoLink.isDisplayed()) {
                System.out.println("Link found and visible.");
            } else {
                System.out.println("Link found but not visible.");
            }
        } catch (Exception e) {
            System.out.println("Link not found.");
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

If the link text is not exact, findElement(By.linkText()) will throw a NoSuchElementException.

Use By.partialLinkText() if you want to find links by part of their text.

Always close the browser after tests to free resources.

Summary

findElement by linkText locates links by their exact visible text.

It is simple and useful for clicking or verifying links during tests.

Make sure the text matches exactly, or the element won't be found.