如何使用Selenium和Python获取元素的href属性
您好,我想在这段HTML代码中获取Href链接,但我无法。我尝试使用XPath,但它只返回了一个错误 Xpath:如何使用Selenium和Python获取元素的href属性,python,selenium,xpath,linktext,partiallinktext,Python,Selenium,Xpath,Linktext,Partiallinktext,您好,我想在这段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="L
//*[@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>
要打印href属性的值,可以使用以下任一选项:
- 使用
:链接文本
print(driver.find_element_by_link_text("Activate your account").get_attribute("href"))
print(driver.find_element_by_partial_link_text("Activate your account").get_attribute("href"))
- 使用部分链接文本:
print(driver.find_element_by_link_text("Activate your account").get_attribute("href"))
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"))
理想情况下,您需要为\u元素\u located()的
可见性\u进行归纳,并且您可以使用以下任一选项:
- 使用
链接文本
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Activate your account"))).get_attribute("href"))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, "Activate your account"))).get_attribute("href"))
- 使用部分链接文本
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Activate your account"))).get_attribute("href"))
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