Search code examples
pythonseleniumxpathcss-selectorsgetattribute

How to get href from class using python?


I want to get link from href from an element. I tried find_elements_by_css_selector but can't reach out it. Does anyone know how to do it?

<a class="name" title="Download" data-i18n="[title]clickToDownload" data-src="some-link" href="link-to-retreive">
</a>

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("a.name[title='Download']").get_attribute("href"))
      
    • Using xpath:

      print(driver.find_element_by_xpath("//a[@class='name' and @title='Download']").get_attribute("href"))
      

    Ideally you need 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, "a.name[title='Download']"))).get_attribute("value"))
      
    • Using XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='name' and @title='Download']"))).get_attribute("value"))
      
    • 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