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
Save the above file with .html and open the file with Google Chrome
It will open as
When you run the below WebDriver code, you will access the first “click here” link
Let’s create a test case in which we will automate the following scenarios to handle linkText:
- Invoke a Google chrome browser.
- Open URL: https://www.facebook.com/
- Click on the Forgotten account? link.
- Close the browser.
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.
Step 3: Right-click on the src folder and click on the New > class.
Give your Class name as “Test_LinkText” and Select the checkbox “public static void main(String[] args) and click on the “Finish” button.
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]