Search code examples
pythonseleniumxpathlinktextpartiallinktext

How to Get the href attribute of the element using Selenium and Python


Hello I want to get the Href link inside this HTML code but I couldn't I tried with the XPath but it just returns an error

The Xpath:

//*[@id="style_16076273510119000593_BODY"]/div/table/tbody/tr/td[2]/table[2]/tbody/tr[3]/td[2]/table/tbody/tr/td/table[3]/tbody/tr/td/table/tbody/tr/td/a

And here is the HTML code

<a type="Link" islinktobetracked="true" target="_blank" linkid="3f21f23defaf3c1dd21e27f700aaef7e" style="text-decoration:none;color:#ffffff !important;white-space: nowrap;" href="https://www.thewebsite.com/signin?" rel=" noopener noreferrer">Activate your account</a>

Solution

  • To print the value of the href attribute you can use either of the following Locator Strategies:

    • Using link_text:

      print(driver.find_element_by_link_text("Activate your account").get_attribute("href"))
      
    • Using partial_link_text:

      print(driver.find_element_by_partial_link_text("Activate your account").get_attribute("href"))
      
    • Using xpath:

      print(driver.find_element_by_xpath("//a[@type='Link' and text()='Activate your account']").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 LINK_TEXT:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Activate your account"))).get_attribute("href"))
      
    • Using PARTIAL_LINK_TEXT:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, "Activate your account"))).get_attribute("href"))
      
    • Using XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@type='Link' and text()='Activate your account']"))).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