首页 > 解决方案 > 从跨度标题中抓取信息

问题描述

我的 html 看起来像这样:

    <h3>Current Guide Price <span title="92">   92
    </span></h3>

我想得到的信息是 92。

这是另一个 html 页面,我需要在其中获取相同的数据:

    <h3>Current Guide Price <span title="4,161">    4,161
    </span></h3>

我需要从此页面获取 4,161。

这是该页面的链接以供参考: http ://services.runescape.com/m=itemdb_oldschool/viewitem?obj=1613

我试过的:

/h3/span[@title="92"]@title

/h3/span[@title="92"]/text()

/div[@class="stats"]/h3/span[@title="4,161"]@title

因为我需要的信息在实际的跨度标签中,所以很难以动态方式获取数据,我可以将其用于许多不同的页面。

标签: python-3.xxpathlxml

解决方案


from lxml import html
import requests


baseUrl = 'http://services.runescape.com/m=itemdb_oldschool/viewitem?obj=2355'
page = requests.get(baseUrl)

tree = html.fromstring(page.content)
price = tree.xpath('//h3/span')
price2 = tree.xpath('//h3/span/@title')
for p in price:
    print(p.text.strip())
for p2 in price2:
    print(p2)

输出92在这两种情况下。


推荐阅读