Beautiful Soup 'ResultSet' 对象没有属性 'text'

问题描述 投票:0回答:3
from bs4 import BeautifulSoup
import urllib.request
import win_unicode_console
win_unicode_console.enable()


link = ('https://pietroalbini.io/')  
req = urllib.request.Request(link, headers={'User-Agent': 'Mozilla/5.0'})
url = urllib.request.urlopen(req).read()

soup =  BeautifulSoup(url, "html.parser")
body = soup.find_all('div', {"class":"wrapper"})

print(body.text)

我对美丽汤有疑问。如果我在末尾没有“.text”的情况下运行此代码,它会显示一个

div
的列表,但如果我在末尾添加“.text”,则会收到错误

Traceback (most recent call last):
 File "script.py", line 15, in <module>
   print(body.text)
AttributeError: 'ResultSet' object has no attribute 'text'
python beautifulsoup
3个回答
9
投票

find_all
返回一个 ResultSet 对象,您可以使用
for
循环对其进行迭代。你能做的是:

for wrapper in body.find_all('div', {"class":"wrapper"}):
   print wrapper.text

4
投票

如果您输入:

print(type(body))

你会看到

body
<class 'bs4.element.ResultSet'>
这意味着 all 与该类匹配的元素。您可以迭代它们:

for div in body:
    print(div.text)

或者如果你知道你只有 div,你可以使用

find
代替:

div = soup.find('div', {"class":"wrapper"})
div.text

1
投票

可能应该作为答案发布..所以正如评论中几乎逐字所述

您的代码应如下所示:

for div in body: 
    print div.text
    #python3
    #print(div.text)

或者您喜欢的一些命名模式。

find_all
方法返回一个生成的列表(此处宽松地使用术语列表),其中包含在递归或非递归解析源网页 html 后,beautifulsoup 发现的与您的条件匹配的项目,具体取决于您的搜索方式。

正如错误所示,生成的对象集没有属性文本,因为它不是元素而是它们的集合。 但是,结果集中的项目(如果找到的话)确实如此。

您可以查看文档这里

© www.soinside.com 2019 - 2024. All rights reserved.