Using Link Text & Partial Link text in Selenium

Learn about link text and partial link text and how to use them in Selenium.

Get Started free
Using Link Text & Partial Link text in Selenium
Home Guide Using Link Text & Partial Link text in Selenium

Using Link Text & Partial Link text in Selenium

Selenium WebDriver offers robust locator strategies for web automation, with Link Text and Partial Link Text being essential for identifying and interacting with hyperlinks.

Link Text locates elements based on the exact text of the link, while Partial Link Text identifies elements using a portion of the link’s text.

These methods enhance the efficiency and accuracy of automated web testing. This article explores the differences between Link Text and Partial Link Text and the steps for locating elements using these strategies.

What is Link Text in Selenium?

Link Text is a Selenium locator strategy used to identify hyperlinks based on their exact textual content. It ensures precise selection by matching the full text of an HTML anchor <a> tag

Syntax of Link Text in Selenium

Here is the syntax for using Link Text in Selenium:.

driver.findElement(By.linkText("Exact Link Text")).click();

Steps to Locate Web Elements Using Link Text in Selenium

Here are the steps to be followed for locating web elements using Link Text in Selenium:

  • Step 1: Configure Selenium WebDriver by installing the necessary libraries and starting browser-specific drivers.
  • Step 2: Use driver.get() method to load target webpage URL. Verify complete page loading and accessibility before performing element interactions.
  • Step 3: Use driver.findElement(By.linkText()) method with exact text matching, considering case sensitivity and unique identification.
  • Step 4: Execute actions like click(), getText(), or getAttribute() on located link element.

Sample Code:

WebDriver driver = new ChromeDriver();

driver.get("https://example.com");



// Locate and click link

WebElement signupLink = driver.findElement(By.linkText("Sign Up"));

signupLink.click();
  • Step 5: Implement robust error management using try-catch blocks and exception handling. Add explicit/implicit waits and logging mechanisms to improve test script reliability.

Complete Code:

from selenium import webdriver

from selenium.webdriver.common.by import By



driver = webdriver.Chrome(executable_path='path_to_chromedriver')



driver.get("https://www.example.com")

try:

link_element = driver.find_element(By.LINK_TEXT, "Exact Link Text Here")  

link_element.click()

print("Link text:", link_element.text)

except Exception as e:

print(f"An error occurred: {e}")



driver.quit()

What is Partial Link Text in Selenium?

Partial Link Text allows locating web elements by matching a portion of the link text, providing more flexibility when exact text is challenging to use.

Steps to Locate Elements Using Partial Link Text in Selenium

Here are some of the steps to follow for locating elements using Partial Link Text in Selenium:

  • Step 1: Before starting with any operations, import the necessary Selenium WebDriver components.
from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys
  • Step 2: Use this code to initialize WebDriver:
driver = webdriver.Chrome(executable_path='path_to_chromedriver')
  • Step 3: Use the get() method to open the target webpage where the link is located.
driver.get("https://www.example.com")
  • Step 4: Use the find_element() method and specify the Partial Link Text locator. The partial_link_text method finds links based on a partial match of the link’s text.
link_element = driver.find_element(By.PARTIAL_LINK_TEXT, "example")
  • Step 5: Once the element is located, you can interact with it by clicking the link or extracting its attributes.
link_element.click()

print(link_element.text)

Complete Code:

from selenium import webdriver

from selenium.webdriver.common.by import By



driver = webdriver.Chrome(executable_path='path_to_chromedriver')

driver.get("https://www.example.com")

try:

link_element = driver.find_element(By.PARTIAL_LINK_TEXT, "example")

link_element.click()

print("Link text:", link_element.text)

except Exception as e:

print(f"An error occurred: {e}")



driver.quit()

Difference Between Link Text and Partial Link Text in Selenium

Here are the key differences between link text and partial link text in Selenium:

ParameterLink TextPartial Link Text
Text MatchingRequires exact text matchAllows partial text match
Case SensitivityCase-sensitiveCase-sensitive
Use CaseBest for stable, unchanging linksIdeal for dynamic or long link texts
Matching CriteriaMust match complete link textMatches text containing specified substring
First Match BehaviorReturns first matching elementReturns first matching element
FlexibilityLess flexibleMore flexible
Recommended WhenLink text is short and consistentLink text is long or variable
PerformanceSlightly fasterMarginally slower

Choosing Between Link Text & Partial Link Text for Multiple Match Results

It’s important to understand the differences in behavior and how each method can be applied effectively.

Some of the common scenarios to use Link Text or Partial Link Text for multiple match results are:

Link Text for Multiple Match Results

Here are the common scenarios to use Link Text for multiple match results:

  • The By.LINK_TEXT locator requires an exact match with the entire link’s text.
  • If the exact text of the link is known, then Link Text is more suitable to pick.
  • If multiple elements share the same exact text, Link Text will return the first match or raise an exception if multiple identical links exist.
  • It is less flexible and may not be ideal for text with variable elements.

Partial Link Text for Multiple Match Results

Here are the common scenarios to use Partial Link Text for multiple match results:

  • The By.PARTIAL_LINK_TEXT locator matches a substring of the link text.
  • This method is best when only some part of the link is known, especially when the text is long or dynamic.
  • This method can return multiple results if there are multiple links with similar or matching text parts. It doesn’t require the full string, allowing links to be matched even if only some parts of the text are known.

Test on Real Devices with BrowserStack Automate

BrowserStack Automate offers a reliable way to run Selenium tests on real devices and browsers without in-house infrastructure. This eliminates the need for emulators or simulators, ensuring more reliable test outcomes.

BrowserStack Automate Banner

Whether a web application or a mobile app is tested, BrowserStack’s cloud-based platform makes it easy to integrate Selenium-based tests into the CI/CD pipeline and effectively perform cross-browser testing.

Some of the key features of Selenium testing with BrowserStack Automate are:

  • Execute Selenium tests across different browser types (Chrome, Firefox, Safari, Edge, etc.) to ensure that the application works for all users.
  • There’s no need for managing devices or testing because of BrowserStack’s cloud-based infrastructure.
  • Easily integrate Selenium tests with popular CI/CD tools like Jenkins, CircleCI, and GitHub Actions.
  • BrowserStack also supports Selenium WebDriver, making it easy to run existing Selenium scripts on real devices without modification.

Best Practices for Using Link Text and Partial in Selenium

Here are some best practices for using Link Text and Partial Link Text in Selenium:

For Link Text:

  • Use Link Text when the link’s full text is known and consistent across sessions.
  • Ensure the link text is unique on the page to avoid conflicts.
  • Avoid using Link Text if the application frequently changes link labels to reduce test maintenance.

For Partial Link Text:

  • Choose Partial Link Text for dynamic or lengthy links where only part of the text is stable.
  • Combine with other locators like XPath for improved accuracy in complex DOM structures.
  • Avoid overly generic partial text to prevent matching unintended elements.

Talk to an Expert

Conclusion

Both Link Text and Partial Link Text are important locator methods in Selenium, with different purposes depending on the need. Link Text is ideal for matching the exact or static text of the links, while Partial Link Text is helpful in matching any particular portion of the link text in case of dynamic or lengthy links.

By understanding their primary usage, the overall reliability and efficiency of the Selenium tests can be improved.

Useful Resources for Selenium

Methods, Classes, and Commands

Configuration

XPath

Locators and Selectors

Waits in Selenium

Frameworks in Selenium

Miscellaneous

Best Practices, Tips and Tricks

Design Patterns in Selenium: Page Object Model and Page Factory

Action Class

TestNG and Selenium

JUnit and Selenium

Use Cases

Types of Testing with Selenium

Tags
Automation Testing Real Device Cloud Selenium Selenium Webdriver