Python美化组以获取数据<span>标记

2022-05-21 07:56:56 发布

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

我正在尝试获取标签数据

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'

请帮帮我! 谢谢


Tags: 数据代码text示例valuehtml标签selectoneclassattributeerrorspanaverageratingbeautifulsoup
1条回答
网友
1楼 ·

如果您想获得值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())