真的很简单。对于以下html代码:

<h1 id="product-name" itemprop="name">Best product name !</h1>


我想检索最好的产品名称!为此,我目前正在使用:

prodname = soup.find(id="product-name")
prodname_clean = list(prodname.children)[0]
print(prodname_clean)


但是在某些情况下,我会收到以下错误消息:

AttributeError: 'NoneType' object has no attribute 'children'


为什么在某些情况下而不是其他情况下会出现此错误,这是一个谜,但是无论如何,我检索h1的方式很可能不是最好的。任何帮助将不胜感激。

最佳答案

您可以简单地做到这一点:

>>> soup.find('h1').text
'Best product name !'


或者更确切地说,

>>> soup.find('h1', {'id': 'product-name'}).text
'Best product name !'


您可以在字典中添加更多属性,例如

{'id': 'product-name', 'itemprop': 'name'}

10-01 03:59
查看更多