首页 > 解决方案 > 如何编写适当的 Xpath 来定位文本值

问题描述

我正在尝试使用 python、selenium 和 xpath 来获取以下 HTML 块中的文本 $0.180,

<div class="wlp-values-div">
  <span class="wlp-last-price-span">$0.180</span>

此代码深入到网站 HTML 中,我尝试使用以下 Xpath 来定位它:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://smallcaps.com.au/stocks/?symbol=AWJ")
time.sleep(3)
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()

ele = driver.find_element_by_xpath("//div[@class='wlp-values-div']/span[@class='wlp-last-price-span']")

但我收到错误:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='wlp-values-div']/span[@class='wlp-last-price-span']"}

任何帮助将不胜感激

标签: pythonselenium-webdriverxpathiframecss-selectors

解决方案


<iframe class="wl-summary" id="wl-summary" src="https://cloud.weblink.com.au/clients/smallcaps/summary/summary.aspx?symbol=AWJ&amp;" width="100%" height="25" frameborder="0" scrolling="no" allowtransparency="true" style="height: 1077px;"></iframe>
<iframe class="wl-quote-frame" src="quoteFrame.aspx?symbol=AWJ&amp;" scrolling="no" frameborder="0" height="1" style="height: 177px;"></iframe>

它位于双嵌套 iframe 中,因此您必须切换到它。这也有适当的等待,而不是使用 time.sleep() 并希望元素加载。它还单击弹出窗口以避开并打印跨度文本。

wait = WebDriverWait(driver, 10)
driver.get("https://smallcaps.com.au/stocks/?symbol=AWJ")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#tve_editor > div'))).click()
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CLASS_NAME, 'wl-summary')))
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CLASS_NAME, 'wl-quote-frame')))
elem=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.wlp-last-price-span')))
print(elem.text)

进口

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

推荐阅读