从html span检索内容字段

时间:2019-03-04 16:08:25

标签: python html web-scraping

我在对象内有以下html代码:

<span itemprop="price" content="187">187,00&nbsp;€</span>

我的想法是获取span对象(价格)的竞争。为此,我正在执行以下操作:

import requests
from lxml import html

tree = html.fromstring(res.content)
prices = tree.xpath('//span[@class="price"]/text()')
print(float(prices[0].split()[0].replace(',','.')))

此处,res.content包含在上面显示的span对象内部。如您所见,我可以从187,00&nbsp;€获取价格(经过一些修改),而从span内的“ content”标签获取价格会更容易。我尝试使用:

tree.xpath('//span[@class="price"]/content()')

但是它不起作用。有没有办法检索这些数据?我愿意使用其他任何库。

2 个答案:

答案 0 :(得分:1)

您可以使用BeautifulSoup库进行html解析:

from bs4 import BeautifulSoup as soup
d = soup('<span itemprop="price" content="187">187,00&nbsp;€</span>', 'html.parser')
content = d.find('span')['content']

输出:

'187'

要更具体地说明事件,可以提供itemprop值:

content = d.find('span', {'itemprop':'price'})['content']

要获取标签之间的内容,请使用soup.text

content = d.find('span', {'itemprop':'price'}).text

输出:

'187,00\xa0€'

答案 1 :(得分:1)

您可以尝试

prices = tree.xpath('//span[@class="price"]')
for price in prices:
    print(price.get("content"))
相关问题