我正在嘗試使用 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[@hljs-string">"]//a"}
uj5u.com熱心網友回復:
您正在使用絕對錯誤的定位器。
所述h2元素類屬性值jobTitle jobTitle-color-purple,而不是title。
子元素標記名稱是span,不是a。
請試試這個:
title = job.find_element_by_xpath('//h2[@]//span').text
您可能需要在此之前添加等待/延遲,以便在您嘗試訪問該元素之前加載頁面。
uj5u.com熱心網友回復:
要列印文本,Director您可以使用以下任一定位器策略:
使用
css_selector和get_attribute("innerHTML"):print(driver.find_element(By.CSS_SELECTOR, "h2.jobTitle > span[title]").get_attribute("innerHTML"))使用
xpath和文本屬性:print(driver.find_element(By.XPATH, "//h2[contains(@class, 'jobTitle')]/span[@title]").text)
理想情況下,你需要引起WebDriverWait的visibility_of_element_located(),你可以使用以下的定位策略:
使用
CSS_SELECTOR和文本屬性: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
您可以在如何使用 Selenium 檢索 WebElement 的文本 - Python 中找到相關討論
參考
鏈接到有用的檔案:
get_attribute()方法Gets the given attribute or property of the element.text屬性回傳The text of the element.- 使用 Selenium 的 text 和 innerHTML 之間的區別
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340408.html
