在python中webscraping时在HTML中定位正确的标记

2024-04-23 10:56:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为学校做一个项目,我显示比特币的当前价格,以太币,也许还有另外一种,还有即时消息网络抓取https://cryptowat.ch/,但是我找不到用来存储实时价格的标签。当我解析div标签时,它会返回价格,但我无法将其分离出来,以便用python显示它

<div class="rankings-col__header__segment"><h2>BTC</h2><weak>usd </weak>10857.00</div>

Tags: 项目https网络div价格col标签h2
1条回答
网友
1楼 · 发布于 2024-04-23 10:56:36

据我所知-您知道BTC字符串,可以使用它来创建定位器。你知道吗

因此,如果是XPath,可以使用它和following-sibling::text()

//h2[. = 'BTC']/following-sibling::text()

使用lxml.html的示例:

from lxml.html import fromstring

data = """<div class="rankings-col__header__segment"><h2>BTC</h2><weak>usd </weak>10857.00</div>"""

root = fromstring(data)
print(root.xpath("//h2[. = 'BTC']/following-sibling::text()"))

打印['10857.00']。你知道吗


如果您碰巧使用BeautifulSoup,那么它将是:

from bs4 import BeautifulSoup


data = """<div class="rankings-col__header__segment"><h2>BTC</h2><weak>usd </weak>10857.00</div>"""

soup = BeautifulSoup(data, "html.parser")
print(soup.find("h2", string="BTC").find_next_sibling(text=True))

相关问题 更多 >