DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })
  • React Callback Refs: What They Are and How to Use Them
  • Process Mining Key Elements

Trending

  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • MCP Servers: The Technical Debt That Is Coming
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • The Future of Java and AI: Coding in 2025

Find Elements With Link Text and Partial Link Text in Selenium

This article goes over the practical implementation of link text and partial link text, as we perform automation testing with Selenium.

By 
Sadhvi Singh user avatar
Sadhvi Singh
·
Jul. 01, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
37.4K Views

Join the DZone community and get the full member experience.

Join For Free

There have been times where I've seen an experienced automation tester taking a longer route for finding an element as they have a habit of sticking to their favorite locator. This is why I thought I would come up with a tutorial series for CSS locators in Selenium to help budding automation testers come up with a strategic implementation of these locators. And to those of us who are experienced, it should be a quick and good recap.

This article will represent the practical implementation of link text and partial link text, as we perform automation testing with Selenium. The links on any web application can help in locating an element with either exact match of the text or through partial matching. Using link text and partial link text in Selenium, we will be able to locate both of these matches. This is the last article of my tutorial series on CSS Locator in Selenium.

You can check out other articles around different CSS locator in Selenium that helps in locating elements through various ways:

  • ID locator in Selenium
  • Name locator in Selenium
  • Class Name locator in Selenium
  • Tagname locator in Selenium
  • CSS Selector in Selenium
  • XPath in Selenium

With that said, let’s find out how to leverage link text and partial link text in Selenium to locate elements on a web page.

Using Link Text in Selenium to Locate an Element

In order to access links using link text in Selenium, the below-referenced code is used:
driver.findElement(By.linkText("this is a link text"));

Note: In a scenario where multiple links have similar text exists, it will automatically select the first one.

Let’s refer the code snippet below to understand the use case. In this case, we are taking Airbnb as an example, where we are clicking on any one stay in Goa through the link match.

selenium locators

The referenced screenshot of the div element with the link text:

selenium locatorsImage title


import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class LinkText {
    public static void main(String[] args) { // TODO Auto-generated method stub          
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");     
  WebDriver driver=new ChromeDriver();     
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);          
  driver.manage().window().maximize();          //Opening the air bnb Goa homestays page     
  driver.get("https://www.airbnb.co.in/s/Goa/all");          
  //locating an element via link text in Selenium now, and clicking on that stay     
  driver.findElement(By.linkText("Standard One Bedroom Suite with Pool & Jacuzzi")).click();              
  driver.quit();   }   }

We can locate the same element using partial link text in Selenium as well. Let’s check how!

Using Partial Link Text in Selenium to Locate an Element

Partial link text in Selenium is another way of locating an element via a link. The only difference from the link text in Selenium to partial link text is that it does not look into the exact match of the string value but works on a partial match. So, in case you are looking for a link with a bigger text length, you can get away from using only the partial link text rather than the whole link text in Selenium.

The syntax of locating an element by partial link text:

driver.findElement(By.partialLinkText ("link text"));

Referencing the above scenario, below is the code snippet for partial link text of the same stay of Airbnb:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class PartialLinkText {
    public static void main(String[] args) { // TODO Auto-generated method stub          
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");     
  WebDriver driver=new ChromeDriver();     
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);          
  driver.manage().window().maximize();          //Opening the air bnb Goa homestays page     
  driver.get("https://www.airbnb.co.in/s/Goa/all");          //locating an element via link text now and clicking on that stay     
  driver.findElement(By.partialLinkText("Pool & Jacuzzi")).click();                
  driver.quit();   }   }

How to Select the Right Link Text When You Have Multiple Match Results

The only thing to remember and to be cautious of while using partial link text in Selenium is when partial link text ends up matching with multiple link text on the page. In this case, make sure you are clicking on the desired one.

Let’s consider another scenario as we perform automation testing with Selenium, where you end up matching multiple link texts and wish to target only the designated one. For the same Airbnbs in Goa, I am trying to locate the element with partial text ‘pool’ in it. So, the strategy would be to find out home many stays have a pool in them, click on the required stay, and post that. The reference code snippet below represents how we can pick the right target out of multiple match results using the partial link text in Selenium.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class LinkText {
    public static void main(String[] args) { // TODO Auto-generated method stub          
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");     
  WebDriver driver=new ChromeDriver();     
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);          
  driver.manage().window().maximize();          //Opening the air bnb Goa homestays page     
  driver.get("https://www.airbnb.co.in/s/Goa/all");          //locating an element via link text now and clicking on that stay     
  List<WebElement> poolNumber=driver.findElements(By.partialLinkText("Pool"));          /
  /find the number of links with the text as pool     int numberOfStaysWithPool= poolNumber.size();          
  System.out.println(numberOfStaysWithPool);          
  for(int k=0; k<numberOfStaysWithPool; k++)     {       //printing all those links       
  System.out.println(poolNumber.get(k).getText());            }          //select the luxury three bedroom apartment link     
poolNumber.get(2).click();                
driver.quit();   }   }

selenium locators output

In the above code snippet, I have used  findElements since I am supposed to receive multiple web elements with the partial text ‘pool.’ Now, using an index, I have navigated to one of the links, which I wish to click. Simple, isn’t it?

Note: Both, link text and partial link text are cases sensitive as CSS locator in Selenium.

For example, assume that a link ‘Register’ is present on a home page and a similar link ‘REGISTER’ is present on the footer of the homepage. In this case, if you are locating with link text ‘REGISTER’, it will automatically select the link in the footer and not the other one.

Conclusion

Link text and partial link text locator in Selenium works only on links of a given web application. If you intend to locate elements other than links you cannot use link text or partial link text locators in Selenium. If you are dealing with links in your application, then this is perhaps the best locator to go with. Happy testing! 

Links Element

Published at DZone with permission of Sadhvi Singh. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })
  • React Callback Refs: What They Are and How to Use Them
  • Process Mining Key Elements

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!