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.
findElement by linkText in 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.
WebElement homeLink = driver.findElement(By.linkText("Home"));WebElement contactLink = driver.findElement(By.linkText("Contact Us"));WebElement emptyLink = driver.findElement(By.linkText(" "));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.
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(); } } }
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.
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.