Open In App

How to get an attribute value from a href link in Selenium java?

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with Selenium WebDriver in Java, automating web interactions often involves handling hyperlinks. A common task is to extract the attribute value from a <a> tag, specifically the href attribute, which contains the link's destination URL. Extracting this href value allows you to verify or manipulate links within your automation scripts.

In this article, we'll guide you on how to get an attribute value from a href link in Selenium Java with an easy-to-understand code example.

Let us discuss it by taking an Example:

HrefLink.java
package com.example.tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

public class HrefLink {
    public static void main(String[] args) {
        // Set the path for the ChromeDriver executable manually
        System.setProperty("webdriver.chrome.driver", "F:\\users\\hp\\Downloads\\chromedriver.exe");
        
        // Initialize the ChromeDriver
        WebDriver driver = new ChromeDriver();
        
        // Set implicit wait before interacting with elements
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        
        // Navigate to the target webpage
        driver.get("https://www.geeksforgeeks.org/trending/");
        
        try {
            // Identify the element using link text
            WebElement linkElement = driver.findElement(By.linkText("Trending Now"));
            
            // Get href value from the link
            String hrefValue = linkElement.getAttribute("href");
            System.out.println("Href value of link: " + hrefValue);
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        } finally {
            // Close the browser and clean up resources
            driver.quit();
        }
    }
}

Explanation:

  • Package : This code is part of the seleniumpractise package.
  • Imports : This imports are brings in necessary Selenium classes.
  • class Declaration : The class is named as HrefLink.
  • Main Method : The entry point of the program where the execution begins.
  • System.setProperty : This method the sets the system property to specify the location of ChromeDriver executable.
  • WebDriver Instance : An instance of ChromeDriver is created, allowing you to control the Chrome browser.
  • Implict Wait : Sets a maximum wait time of 5 seconds for elements to be found before throwing a NoSuchElementException.
  • Navigate: The get( ) method loads the specified URL in the browser.
  • Locate the Element : The findElement( ) method locates the anchor tag (<a>) with the exact text "Trending Now". This returns a WebElement representing the link.
  • Get Attribute : This getAttribute("href") method retrieves the value of the href attribute from the located element.
  • Print Statement : The value of the href is printed to the console.
  • Close Driver : This closes the current browser window. It's good practice to clean up resources after your automation task is complete.

Output:

output
Output

Conclusion

To get an attribute value from a href link in Selenium Java, simply use the getAttribute("href") method. This allows you to access the URL of any hyperlink and perform further actions, such as validation or navigation. Understanding how to extract attributes efficiently can enhance your automation tests and ensure your scripts handle web elements dynamically.

By applying Selenium’s ability to retrieve attribute values, you can easily validate and interact with web elements in your test cases.


Next Article
Article Tags :

Similar Reads