Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to get text from the alert box in java Selenium Webdriver?
Next article icon

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
How to get text from the alert box in java Selenium Webdriver?

S

sunilgacd6r
Improve
Article Tags :
  • Selenium

Similar Reads

  • How to click a link whose href has a certain substring in Selenium java?
    A webpage can contain one or more hypertexts referencing other websites with the help of hyperlinks. This is enabled using the HTML anchor tag which has an attribute named href which takes the string value of the hyperlink. In this article, we will be demonstrating how to find specific anchor tags a
    4 min read
  • How to Get All Available Links on the Page using Selenium in Java?
    Selenium is an open-source Web-Automation tool that is used to automate web Browser Testing. The major advantage of using selenium is, that it supports all major web browsers and works on all major Operating Systems, and it supports writing scripts on various languages such as Java,  JavaScript, C#
    2 min read
  • How to get Attribute Value from XML using JavaScript?
    To get the attribute values from XML in JavaScript, We can use DOM manipulation or XPath querying and even use regular expressions to efficiently retrieve attribute values from XML documents. Below are the approaches to get attribute value from XML with Java Script: Table of Content Using DOM Parser
    3 min read
  • How to Run Gecko Driver in Selenium Using Java?
    Selenium is a well-known software used for software testing purposes. It consists of three parts: Selenium IDE, Selenium WebDriver, and Selenium Grid. Selenium WebDriver is the most important. Using WebDriver, online website testing can be done. There are three main WebDriver implementations: Chrome
    5 min read
  • How to get text from the alert box in java Selenium Webdriver?
    In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert
    3 min read
  • How to insert a JavaScript variable inside href attribute?
    To insert a JavaScript variable inside the href attribute of an HTML element, <a > ... </a> tags are used. One of the attributes of 'a' tag is 'href'. href: Specifies the URL of the page the link goes to. Below are the Methods to use Variables inside this 'href' attribute: Table of Conte
    3 min read
  • How to click on an image using Selenium in Java?
    Selenium, a popular tool for automating web application testing across browsers, often requires image interaction. In this article we will discuss how to clicking on image using Selenium in Java. PrerequisitesJava Development Kit (JDK) installed.Selenium WebDriver library added to your project.A sup
    3 min read
  • How to automate google Signup form in Selenium using java?
    For any QA engineer or developer, automating the Google Signup form with Selenium may be a hard nut to crack. Also, as the needs are increasing toward automated testing, in this article, we will learn how to deal with a complicated web form like Google Signup. We will show you how to automate the Go
    4 min read
  • How to get innerHTML of whole page in selenium java driver?
    When automating web applications with Selenium WebDriver in Java, it's often necessary to retrieve the entire HTML content of a webpage. This can be useful for testing purposes, data extraction, or validating the structure of the page. Selenium WebDriver provides a straightforward way to access the
    3 min read
  • How to Drag and Drop an Element using Selenium WebDriver in Java?
    Selenium is an open-source web automation tool that supports many user actions to perform in the web browser. Automating a modern web page that has a drag and drop functionality and drag and drop is used to upload the files and so many user activities. so to perform the drag and drop actions the sel
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences