Search code examples
javaseleniumxpathcss-selectorswebdriverwait

Get href attribute of an element of a web page using Selenium


I have this, but it returns the URL of the web page. I want the "href" in a text string.

PATH_DATA = //[@id="vvp-product-details-modal--product-title"][@class="a-link-normal"]
WebElement myData = driver.findElement(By.xpath(PATH_DATA));
String url = myData.getAttribute("href")

It returns the URL of the web page. I want the "href" in a text string.

Snapshot:

Enter image description here


Solution

  • To print the value of the href attribute you can use either of the following locator strategies:

    • Using cssSelector:

      System.out.println(wd.findElement(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title")).getAttribute("href"));
      
    • Using xpath:

      System.out.println(wd.findElement(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']")).getAttribute("href"));
      

    Ideally, to extract the the value of the href attribute, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

    • Using cssSelector and getText():

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title"))).getAttribute("href"));
      
    • Using xpath and getAttribute("innerHTML"):

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("href"));