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

SeleniumAutomation TestingTesting Tools

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.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class HrefVal{
   public static void main(String[] args) {
      System.setProperty("", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      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);


Published on 26-Oct-2020 11:14:58