Locating Elements using Link Text and Partial Link Text in Selenium WebDriver

Locating Elements using Link Text and Partial Link Text in Selenium WebDriver

Table of Contents

In Selenium WebDriver Links can be accessed by using exact text match or partial text match of their link text. In this article, we learn about the available methods to find and access the links using selenium webdriver.

Accessing links using By.linkText()

In Selenium Webdriver we can access the exact link text by using the method By.linkText(). If we have the same link text for two links, this By.linkText() method will only access the first one. Consider the below HTML code

html.png

Save the above file with .html and open the file with Google Chrome

open.PNG

It will open as

click.PNG

When you run the below WebDriver code, you will access the first “click here” link

code.PNG

Let’s create a test case in which we will automate the following scenarios to handle linkText:

Now, we will create a test case step by step to understand linkText in WebDriver.

Step 1: Launch Eclipse IDE.

Step 2: Go to File > New > Click on Java Project.

File.PNG

Step 3: Right-click on the src folder and click on the New > class.

link.PNG

Give your Class name as “Test_LinkText” and Select the checkbox “public static void main(String[] args) and click on the “Finish” button.

name.PNG

Step 4: Invoke the Google Chrome browser and set the system property to the path of your chromedriver.exe file.

Here is the sample code to set Chrome driver system property:

[box type=”shadow” align=”” class=”” width=””]// System Property for Chrome Driver   

 System.setProperty(“webdriver.chrome.driver”, D:\\Drivers\\geckodriver.exe);  [/box]

After that, we have to initialize the Chrome driver using ChromeDriver Class. Below is the sample code to initialize Chrome driver using ChromeDriver class.

[box type=”shadow” align=”” class=”” width=””]// Instantiate a ChromeDriver class.      

WebDriver driver=new ChromeDriver();  [/box]

We will get the below code to launch the Google Chrome browser after combining both of the above codes.

[box type=”shadow” align=”” class=”” width=””]System.setProperty(“webdriver.chrome.driver”, D:\\Drivers\\geckodriver.exe);  

WebDriver driver=new ChromeDriver();  [/box]

After that, we need to navigate to the desired URL.

Below is the sample code to navigate to the desired URL:

[box type=”shadow” align=”” class=”” width=””]// Launch Website  

driver.navigate().to(“https://www.facebook.com/“);[/box]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class