如何使用 python 从 class 获取 href?
How to get href from class using python?
我想从元素的 href 中获取 link。我尝试 find_elements_by_css_selector 但无法联系到它。有人知道怎么做吗?
<a class="name" title="Download" data-i18n="[title]clickToDownload" data-src="some-link" href="link-to-retreive">
</a>
要打印 href 属性的值,您可以使用以下任一方法 :
使用css_selector
:
print(driver.find_element_by_css_selector("a.name[title='Download']").get_attribute("href"))
使用xpath
:
print(driver.find_element_by_xpath("//a[@class='name' and @title='Download']").get_attribute("href"))
理想情况下,您需要为 visibility_of_element_located()
引入 ,您可以使用以下任一方法 :
使用CSS_SELECTOR
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.name[title='Download']"))).get_attribute("value"))
使用XPATH
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='name' and @title='Download']"))).get_attribute("value"))
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
在每个链接上调用 get_attribute
:
links = browser.find_elements_by_partial_link_text('##')
for link in links:
print(link.get_attribute("href"))
或
lnks=driver.find_elements_by_tag_name("a")
# traverse list
for lnk in lnks:
# get_attribute() to get all href
print(lnk.get_attribute(href))
driver.quit()
我想从元素的 href 中获取 link。我尝试 find_elements_by_css_selector 但无法联系到它。有人知道怎么做吗?
<a class="name" title="Download" data-i18n="[title]clickToDownload" data-src="some-link" href="link-to-retreive">
</a>
要打印 href 属性的值,您可以使用以下任一方法
使用
css_selector
:print(driver.find_element_by_css_selector("a.name[title='Download']").get_attribute("href"))
使用
xpath
:print(driver.find_element_by_xpath("//a[@class='name' and @title='Download']").get_attribute("href"))
理想情况下,您需要为 visibility_of_element_located()
引入
使用
CSS_SELECTOR
:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.name[title='Download']"))).get_attribute("value"))
使用
XPATH
:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='name' and @title='Download']"))).get_attribute("value"))
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
在每个链接上调用 get_attribute
:
links = browser.find_elements_by_partial_link_text('##')
for link in links:
print(link.get_attribute("href"))
或
lnks=driver.find_elements_by_tag_name("a")
# traverse list
for lnk in lnks:
# get_attribute() to get all href
print(lnk.get_attribute(href))
driver.quit()