0

I'm using Python3 and Selenium. The xpath below points to a link. I would like to print the URL. If I write print(link.text) I get the displayed text portion of the link only. For example: link.text in the following link would give me "link text" when I want URL.

HTML:

<a href="url">link text</a>

Code trials:

path = f"/html/body/div/section[5]/div/div/div[1]/div[3]/div[{str(n)}]/div/div[1]/div/div[2]/div[1]/a"
link = driver.find_element_by_xpath(path)
print(link.url) 
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Mike C.
  • 1,761
  • 2
  • 22
  • 46

2 Answers2

2

You need to use

link.get_attribute('href')

instead of

link.text
DonnyFlaw
  • 581
  • 3
  • 9
1

print(link.text) would print the text / textContent / innerHTML of the <a> WebElement i.e.

link text

If your usecase is to print the value of the href attribute i.e. url you can use the following solution:

print(link.get_attribute("href"))
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352