Do you know how to click on the link without using complicated locators like XPath and CSS selectors? linkText in Selenium is a specially designed element locator that locates and interacts with hyperlinks on a page. Whether you are just starting out or looking to use it effectively in your selenium tests, this guide will help you understand how Link Text works, when to use it, and a few tips to make your automation scripts cleaner and more reliable.
What is linkText in Selenium?
ByLinkText is a concrete class inside the By class in Selenium. It is responsible for finding elements by the exact visible link text.
In simple words, linkText is a locator strategy in Selenium WebDriver that is used to identify hyperlinks (<a> tags) on a web page by their exact visible text.
How It Works behind the scenes:
When you use this Selenium locator in a test, it will search for an <a> tag whose text content exactly matches the string you pass.
If Selenium finds a hyperlink with matching text, it will interact with it to perform your given task like click on it, get text, etc.
When to Use
- link text is unique on the page.
- It is static and doesn’t change dynamically.
- You are looking for a quick and easy way to locate a hyperlink.
Syntax of linkText
I don't know in which language you are working. Selenium supports multiple languages. So I am providing link text locator syntax for popular languages, Java, Python, and C#.
Java Syntax
driver.findElement(By.linkText("Exact Link Text")).click();
Python Syntax
driver.find_element(By.LINK_TEXT, "Exact Link Text").click()
C# Syntax
driver.FindElement(By.LinkText("Exact Link Text")).Click();
Step-by-Step: Using linkText in Selenium
Here is a step-by-step guide on how to use link text element locator in Selenium WebDriver.
Step 1: Set Up Selenium WebDriver
Make sure that selenium is installed and configured properly in your project. If not configured, you can follow these Selenium installation guidelines.
// Import necessary Selenium packages
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
Step 2: Update Chrome Browser and Download Latest ChromeDriver
For beginners, it is recommended to run initial tests on the Chrome browser. So, update your Chrome browser to the latest version and download the latest version of ChromeDriver. Here is a guideline to download the latest version of ChromeDriver and update the Chrome browser.
If you are using the Edge browser, here is a guide on how to download the latest EdgeDriver for Selenium.
Step 3: Launch the Browser
Create a WebDriver instance and open a browser (like Chrome).
// Set up ChromeDriver path (optional depending on your setup)
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
Step 4: Navigate to the Web Page
Open the website where you want to click a link. We will use an example link. You can replace it with your testing URL.
driver.get("https://example.com");
Step 5: Locate the Link by Its Text and Click on It
Use By.linkText() method to find the link with the exact visible text and click() method to click on it. You need to replace link text, i.e. "Exact Link Text" as per your original link text.
//Locate link by exact link text WebElement yourLinkText = driver.findElement(By.linkText("Click Here")); //click on link yourLinkText.click();
The above code will locate and click on the link.
Tips:
- Exact Text Match: It is case-sensitive. Also make sure you are using exact text.
- Only for <a> Tags: This locator strategy works only with anchor tags (<a> elements).
- Avoid Extra Spaces: Remove leading/trailing whitespace from text.
- Use partialLinkText(): If you know only part text of the link, use partialLinkText() instead of linkText().
Common Use Cases:
You can use this method for the below given real world test scenarios.
- Navigating to different pages through hyperlinks.
- Clicking buttons styled as links.
- Automating simple workflows with clickable link text.
linkText examples in Java, Python, and C# for Selenium WebDriver
Here is a basic example code for learners on how to use linkText in Java, Python, and C# languages.
Note: Please replace chromedriver path, test URL, and link text with your own ones before running any of the below given examples.
Java Example
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) {
// Set path to chromedriver if necessary
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize the ChromeDriver
WebDriver driver = new ChromeDriver();
try {
// Open the webpage
driver.get("https://example.com");
// Find the link by its exact text and click it
WebElement link = driver.findElement(By.linkText("Contact Us"));
link.click();
} finally {
// Close the browser
driver.quit();
}
}
}
Python Example
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize the Chrome driver
driver = webdriver.Chrome()
try:
# Open the webpage
driver.get("https://example.com")
# Find the link by its exact text and click it
link = driver.find_element(By.LINK_TEXT, "Contact Us")
link.click()
finally:
# Close the browser
driver.quit()
C# Example
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
class LinkTextExample
{
static void Main(string[] args)
{
// Initialize ChromeDriver
IWebDriver driver = new ChromeDriver();
try
{
// Open the webpage
driver.Navigate().GoToUrl("https://example.com");
// Find the link by its exact text and click it
IWebElement link = driver.FindElement(By.LinkText("Contact Us"));
link.Click();
}
finally
{
// Close the browser
driver.Quit();
}
}
}
Handling Multiple Links with Identical Link Text
If Selenium will find multiple links with the same link text on the page, it will only return the first matching element.
Example Scenario:
Suppose a page has hyperlinks like below.
<a href="https://example.com/pagex">View Product</a>
<a href="https://example.com/pagey">View Product</a>
<a href="https://example.com/pagez">View Product</a>
If you run this in Selenium:
WebElement link = driver.findElement(By.linkText("View Product"));
link.click();
Selenium will click only the first <a> element:
<a href="https://example.com/pagex">View Product</a>
When multiple links are present on the page, and if you want to click on the second link, then you can use the following code.
// Find all links with the exact link text
List<WebElement> links = driver.findElements(By.linkText("View Product"));
// Click the second link (index 1, since list is zero-based)
if (links.size() >= 2) {
links.get(1).click();
} else {
System.out.println("Second link not found!");
}
Here, we have used the findElements method to get a list of links from the page with the View Product text. Then the code will check if more than two links are present in the list, then it will kick on the second link using the index value.
However, it is advised to use XPath i.e. By.xpath("(//a[text()='View Product'])[2]") if multiple links with the same text are present on the page and you want to click on a specific link.
If you want to click on all three links, you can use a for loop to iterate and click on them one by one, as the example below.
List<WebElement> links = driver.findElements(By.linkText("View Product"));
for (WebElement link : links) {
System.out.println(link.getAttribute("href")); // Prints each link's URL
// link.click(); // Optional: Click each link (but be cautious, as clicking may navigate away)
}
Pro Tip!: Do not use linktext locator in Selenium if text of link changes frequently. Instead you can use partialLinkText, XPath, or CSS selectors.
Real world Examples
Using the link text element locator, you can not only click on the link. But you can use it for many different purposes. Here are practical examples on how and when you can use linkText in Selenium automation.
Example 1: Extract and Print the Link Text
You can get and print the text of a link to verify if it's correct.
// Find the link element
WebElement link = driver.findElement(By.linkText("About Us"));
// Get the visible text of the link
String linkText = link.getText();
// Print the link text
System.out.println("Link Text is: " + linkText);
Example 2: Retrieve the URL (href Attribute) of the Link
You can fetch the href value to verify if the URL is correct or not.
WebElement link = driver.findElement(By.linkText("Contact Us"));
// Get the 'href' attribute value (the destination URL)
String linkURL = link.getAttribute("href");
System.out.println("The link points to: " + linkURL);
Example 3: Count How Many Links Are on the Page with Specific Text
You can find out how many times a link with a specific text appears on a page.
List<WebElement> links = driver.findElements(By.linkText("Click here"));
System.out.println("Number of 'Cclick here' links: " + links.size());
Example 4: Verify If a Specific Link Is Displayed/Enabled
You can check if a link is visible or enabled on the page before performing actions.
WebElement link = driver.findElement(By.linkText("Terms of Service"));
if(link.isDisplayed() && link.isEnabled()) {
System.out.println("The link is visible and clickable.");
} else {
System.out.println("The link is not ready to interact with.");
}
Example 5: Validate Broken Links Without Clicking
You can use it to locate a link and then send an HTTP request to the href URL to check if the link is broken or working.
WebElement link = driver.findElement(By.linkText("About Us"));
String linkURL = link.getAttribute("href");
// (Assume you have an HTTP client here)
if(checkIfLinkIsBroken(linkURL)) {
System.out.println("The link is broken: " + linkURL);
} else {
System.out.println("The link works fine!");
}
So this way, you can use it for different purposes.
Difference Between linkText and partialLinkText
Main difference between link text and partial link text is: linkText matches the full visible text of the link while partialLinkText matches part of the link text. linkText is a strict element locator, but partialLinkText is more flexible.
Advantages:
Here is a list of advantages of using linktext locator in Selenium automation.
- Simple and Readable: It is very simple to understand.
- Precise: Very useful locator when the link text is unique.
- Direct: No need to deal with complex locators like XPath or CSS.
Limitations:
Please consider these limitations before using linktext locator in your automation tests.
- Exact Match Required: If the text of the link changes or has a leading/trailing space, it can fail.
- Case-Sensitive: Some browsers treat links differently. Use the same link text as per actual on the page.
- Not for Partial Matches: It doesn’t work if you only know part of the text.
Best Practices
Follow these best practices for better performance in Selenium automation when using link text.
- Ensure Uniqueness: Make sure the link text is unique on the page.
- Avoid Long or Dynamic Texts: If the link text is long or dynamic, prefer to use partialLinkText, XPath, or CSS Selectors.
- Trim Spaces: Remove extra spaces in the text.
- Localization: Avoid linkText for multilingual pages.
Final Words
linkText is a simple and beginner-friendly locator strategy in Selenium WebDriver. It’s highly effective when you need to interact with hyperlinks that have clear, static, and unique visible text.
No comments:
Post a Comment