[英]Get text from span tag with Python and Selenium
我正在嘗試使用 Python 和 Selenium 來獲取這個元素。
<h2 class="jobTitle jobTitle-color-purple">
<span title="Director">Director=</span>
<h2>
這是我嘗試過的:
try:
title = job.find_element_by_xpath('.//td[@class="title"]//a').text
except:
title = job.find_element_by_xpath('.//h2[@class="title"]//a').get_attribute(name="title")
我究竟做錯了什么?
no such element: Unable to locate element: {"method":"xpath","selector":".//h2[@class="title"]//a"}
您使用的是絕對錯誤的定位器。
h2
元素類屬性值為jobTitle jobTitle-color-purple
,而不是title
。
子元素標簽名稱是span
,而不是a
。
請試試這個:
title = job.find_element_by_xpath('//h2[@class="jobTitle jobTitle-color-purple"]//span').text
您可能需要在此之前添加等待/延遲,以便在您嘗試訪問該元素之前加載頁面。
要打印文本Director
,您可以使用以下任一Locator Strategies :
使用css_selector
和get_attribute("innerHTML")
:
print(driver.find_element(By.CSS_SELECTOR, "h2.jobTitle > span[title]").get_attribute("innerHTML"))
使用xpath
和text屬性:
print(driver.find_element(By.XPATH, "//h2[contains(@class, 'jobTitle')]/span[@title]").text)
理想情況下,您需要為visibility_of_element_located()
引入WebDriverWait ,並且您可以使用以下任一Locator Strategies :
使用CSS_SELECTOR
和text屬性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.jobTitle > span[title]"))).text)
使用XPATH
和get_attribute("innerHTML")
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[contains(@class, 'jobTitle')]/span[@title]"))).get_attribute("innerHTML"))
注意:您必須添加以下導入:
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()
方法Gets the given attribute or property of the element.
text
屬性返回The text of the element.
從頁面獲取文本
Des = driver.find_element_by_xpath('//*[@class="class name of required data"]').text
這里只有你想從中獲取文本的 span 標簽的類名
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.