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


We can get an attribute value from a href link in Selenium. To begin with, we have to first identify the element having an anchor tag with the help of any of the locators like css, id, class, and so on.

Next, we shall use the getAttribute method and pass href as a parameter to the method. Let us investigate an element with an anchor tag having the href attribute. Here, the value of href should contain /about/about_team.htm.

Example

Code Implementation.

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 HrefValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_team.htm");
      // identify element
      WebElement l = driver.findElement(By.linkText("Team"));
      // href value from getAttribute()
      String v = l.getAttribute("href");
      System.out.println("Href value of link: "+ v);
      driver.close();
   }
}

Output

Updated on: 28-Dec-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements