Search code examples
pythonseleniumxpathcss-selectorsgetattribute

Python Selenium: How can I print the link?


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>

Solution

  • 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