How to Get href Value in Selenium Webdriver Java

Selenium is an open-source web-based automation tool that is implemented using a web driver. We will be using geckodriver because Selenium 3 enables geckodriver as the default WebDriver implementation for Firefox.

Pre-requisites:

  1. geckodriver.exe
  2. maven dependency selenium
 <dependency>
    <groupid>org.seleniumhq.selenium</groupid>
	<artifactid>selenium-java</artifactid>  
	<version>4.1.1</version> 
 </dependency>

Steps:

Getting href value takes 4 simple steps:
  1. Set webdriver.gecko.driver and its' path as a system property.
  2. Set the firefox diver and browse to the website.
  3. Get the HTML Div containing anchor tag as Web-element using webdriver.findElement() function and css selector.
  4. Get the href attribute and print.

Let’s see all the above steps in the code. We will use Webelment.getAttribute(String name) function to get the value of href.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GetHrefValue {
    public static String GECKODRIVER_PATH ="F:\\WORK\\SeleniumShortTasks\\HrefValue\\src\\main\\resources\\geckodriver.exe";
    public static void main(String[] args) {
        //set firefox webdriver
        System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH);
        WebDriver driver = new FirefoxDriver();

        //get the firefox browser & Browse the Website for text
        String siteLink = "https://www.google.com.pk/search?q=selenium&sxsrf=ALiCzsamJQcQ2jjFb80dwEnsrjbTZrD0jQ%3A1659399526569&ei=Zm3oYoOkIsKC9u8PoZmloAM&ved=0ahUKEwiD78j68Kb5AhVCgf0HHaFMCTQQ4dUDCA4&uact=5&oq=selenium&gs_lcp=Cgdnd3Mtd2l6EAMyBAgjECcyBAgjECcyBAgjECcyCggAELEDEIMBEEMyBAgAEEMyBAgAEEMyCggAELEDEIMBEEMyCwgAEIAEELEDEIMBMgUIABCABDIFCAAQgAQ6BwgAEEcQsAM6BwgAELADEEM6CggAEOQCELADGAE6FQguEMcBENEDENQCEMgDELADEEMYAjoMCC4QyAMQsAMQQxgCOhAIABCABBCHAhCxAxCDARAUOgcIIxDqAhAnOgoILhDHARDRAxBDOggIABCxAxCDAToECC4QQzoRCC4QgAQQsQMQgwEQxwEQ0QM6BwguELEDEEM6BwgAELEDEEM6CgguELEDEIMBEENKBAhBGABKBAhGGAFQ3QZYnCFgtCNoAnABeASAAbICiAHPG5IBBjItMTEuMpgBAKABAbABCsgBE8ABAdoBBggBEAEYCdoBBggCEAEYCA&sclient=gws-wiz";
        driver.get(siteLink);


        //Get Heading Div
        WebElement headingDiv = driver.findElement(By.cssSelector("div.kno-rdesc"));
        //Get element with tag a
        WebElement span = headingDiv.findElement(By.tagName("a"));
        System.out.println("Href Value = "+span.getAttribute("href"));
    }
}

Output:

All resources used in this tutorial are attached:
  • source code
  • geckdriver.exe
Download

Comments