1

您好,我想在此 HTML 代码中获取 Href 链接,但我无法尝试使用 XPath,但它只会返回错误

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

这是HTML代码

<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>
4

1 回答 1

1

要打印href属性的值,您可以使用以下任一Locator Strategies

  • 使用link_text

    print(driver.find_element_by_link_text("Activate your account").get_attribute("href"))
    
  • 使用partial_link_text

    print(driver.find_element_by_partial_link_text("Activate your account").get_attribute("href"))
    
  • 使用xpath

    print(driver.find_element_by_xpath("//a[@type='Link' and text()='Activate your account']").get_attribute("href"))
    

理想情况下,您需要诱导WebDriverWait并且visibility_of_element_located()您可以使用以下任一Locator Strategies

  • 使用LINK_TEXT

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

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

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@type='Link' and text()='Activate your account']"))).get_attribute("href"))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
于 2020-12-11T22:26:42.190 回答