python - 如何编写适当的 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']"}
任何帮助将不胜感激
解决方案
<iframe class="wl-summary" id="wl-summary" src="https://cloud.weblink.com.au/clients/smallcaps/summary/summary.aspx?symbol=AWJ&" width="100%" height="25" frameborder="0" scrolling="no" allowtransparency="true" style="height: 1077px;"></iframe>
<iframe class="wl-quote-frame" src="quoteFrame.aspx?symbol=AWJ&" 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
推荐阅读
- javascript - Javascript - 本地存储
- qt - 如何在 QString 文字中指定 utf-8 代码?
- reactjs - 如何在 create-react-app 中更改 TypeScript 代码的 outputDir (/build)
- javascript - 如何在 vue js 富文本编辑器中显示内容?
- html - 悬停时制作 React Bootstrap NavDropdown 下拉菜单
- python - Python 参数传递开销和对象引用
- cmake - CMake:将 add_subproject 与使用 Include 的库一起使用会导致错误的相对路径
- c++ - 特征懒惰评估和临时:一些案例研究
- jestjs - React 酶 + jest 如何测试 onSubmit
- testing - CMake/CTest - 并行执行进程作为测试