1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
g123
  • 13
  • 4
  • It is the first code of code syntactically correct? – Peter Mortensen Nov 28 '22 at 00:45
  • The title is somewhat misleading (thus top search engine hits may lead to here (e.g. for "`href attribute Selenium`")). If the element reference (`myData` in the example) is ***already the correct one***, then `getAttribute` works just fine ([`getAttribute("href")` in Java](https://www.selenium.dev/documentation/webdriver/elements/finders/#tabs-10-1), `get_attribute("href")` in Python, `GetAttribute("href")` in C#, `attribute("href")` in Ruby, `getAttribute("href")` in JavaScript, and `getAttribute("href")` in [Kotlin](https://en.wikipedia.org/wiki/Kotlin_(programming_language))...). – Peter Mortensen Nov 28 '22 at 01:36
  • Or in other words, if the element reference is already the correct one, then trying to use CSS or XPath selectors just to get an attribute ("href" in this case) of an element is way too complicated (and unnecessary). – Peter Mortensen Nov 28 '22 at 01:36

2 Answers2

0

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"));
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

Something like this is your best bet:

href = driver.execute_script("return document.querySelector('#vvp-product-details-modal--product-title')?.href")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pguardiario
  • 53,827
  • 19
  • 119
  • 159