How to get the content of href within some targeted class using selenium?


We can get the content of href within some targeted class with Selenium webdriver. First of all we have to locate the element with an anchor tag having a specific class attribute value with the help of locators like xpath, css or classname.

Then we have to take the help of getAttribute method and pass href as an argument to the method. Let us have a look at the html code of an element with an anchor tag having the class and href attribute. The href value of the element should be /account/register?hl=en.

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 HrefVal{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element with specific class value
      WebElement m= driver.findElement(By.className("login-registrationBoldLink"));
      // getAttribute() to href value
      String val = m.getAttribute("href");
      System.out.println("Href value of targeted: "+ val);
      driver.close()
   }
}

Output

Updated on: 26-Oct-2020

686 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements