2

How can I print the value of the href attribute?

<a href="aaaaa.pdf"></a>

How can I print the link aaaaa.pdf with python selenium?

HTML:

<div class="xxxx">
    <a href="aaaaa.pdf"></a>
</div>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
ADAM
  • 63
  • 1
  • 1
  • 6

4 Answers4

1

You can do like this:

print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href'))
Ari
  • 75
  • 1
  • 8
  • thank you for you answer, None, output. – ADAM Apr 20 '22 at 11:12
  • ```print(driver.find_element_by_css_selector(".xxxx > a").get_attribute('href'))``` or ```print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href')) ```sorry, I forgot the anchor tag – Ari Apr 20 '22 at 11:30
  • no problem :), output "https://xxxxx.com › xxxx..." not link, its a text.. I want link. Thank you for answer :) – ADAM Apr 20 '22 at 11:52
0

Try the below:

   pName = driver.find_element_by_css_selector(".xxxx").text
    print(pName)

or

   pName = driver.find_element_by_css_selector(".xxxx").get_attribute("href")
   print(pName)
Akzy
  • 1,817
  • 1
  • 7
  • 19
0
div.xxxx a

first, check if this CSS_SELECTOR is representing the desired element.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the css and see, if your desired element is getting highlighted with 1/1 matching node.

If yes, then use explicit waits:

wait = WebDriverWait(driver, 20)
print(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.xxxx a"))).get_attribute('href'))

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
0

The value of the href attribute i.e. aaaaa.pdf is within the <a> tag which is the only descendant of the <div> tag.


Solution

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

  • Using css_selector:

    print(driver.find_element(By.CSS_SELECTOR, "div.xxxx > a").get_attribute("href"))
    
  • Using xpath:

    print(driver.find_element(By.XPATH, "//div[@class='xxxx']/a").get_attribute("href"))
    

To extract the value ideally you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.xxxx > a"))).get_attribute("href"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xxxx']/a"))).get_attribute("href"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352