Python BeautifulSoup-获取数据<span>标签

时间:2019-10-17 03:27:24

标签: python beautifulsoup

我正在尝试获取标签数据。

示例html:

<span class=\"value\">3.99<\/span> average rating,\n

这是我的代码:

d = BeautifulSoup(fstuff.text, 'html.parser')
d.select_one("span.average").text

但是我得到了这个错误:

--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-b6b8329a8fe3> in <module>()
----> 1 d.select_one("span.average").text
AttributeError: 'NoneType' object has no attribute 'text'

请帮帮我! 谢谢!

1 个答案:

答案 0 :(得分:0)

如果要获取值3.99,请使用

print(soup.select_one('span.value').text)

如果您想获得average rating,,请使用next_sibling

print(soup.select_one('span.value').next_sibling.strip())

代码:

from bs4 import BeautifulSoup
html='''<span class=\"value\">3.99</span> average rating,\n'''
soup=BeautifulSoup(html,'html.parser')
print(soup.select_one('span.value').text)
print(soup.select_one('span.value').next_sibling.strip())