为什么在Python中使用BeautifulSoup时出现 “‘ResultSet’没有属性‘findAll’”?

8 投票
1 回答
15329 浏览
提问于 2025-04-15 12:14

我正在慢慢学习Python,想写一个简单的函数,从一个在线游戏的高分页面获取数据。这段代码是别人写的,我把它改成了一个函数(这可能是问题所在),但是我遇到了一个错误。以下是代码:

>>> from urllib2 import urlopen
>>> from BeautifulSoup import BeautifulSoup
>>> def create(el):
    source = urlopen(el).read()
    soup = BeautifulSoup(source)
    get_table = soup.find('table', {'id':'mini_player'})
    get_rows = get_table.findAll('tr')
    text = ''.join(get_rows.findAll(text=True))
    data = text.strip()
    return data

>>> create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')
  File "<pyshell#17>", line 6, in create
    text = ''.join(get_rows.findAll(text=True))
AttributeError: 'ResultSet' object has no attribute 'findAll'

提前谢谢你们。

1 个回答

19

哇,Triptych 给了一个关于相关问题的 很棒 的回答

我们可以看到,从 BeautifulSoup 的源代码 来看,ResultSetlist 的一个子类。

在你的例子中,get_rows 是 BS 的 ResultSet 类的一个实例,
而因为 BS 的 ResultSetlist 的子类,所以这意味着 get_rows 是一个列表

作为 ResultSet 的实例,get_rows 没有 实现 findAll 方法;这就是你出错的原因。
Triptych 不同的做法是 遍历 这个列表。
Triptych 的方法之所以有效,是因为 get_rows 列表中的项目是 BS 的 Tag 类的实例;这个类有一个 findAll 方法。

所以,要修复你的代码,你可以把 create 方法最后三行替换成类似这样的内容:

for row in get_rows:
    text = ''.join(row.findAll(text=True))
    data = text.strip()
    print data

给 Leonard Richardson 的备注:我绝对不是想贬低你的作品质量,只是想称它为 BS ;-)

撰写回答