8

所以我正在慢慢学习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'

提前致谢。

4

1 回答 1

19

哇。三联画为相关问题提供了很好的答案。

我们可以从 BeautifulSoup 的源代码中看到ResultSet子类list

在您的示例中,get_rows是 BSResultSet类的一个实例,
并且由于 BS 的ResultSetsubclasses list,这意味着get_rows 是一个 list

get_rows,作为 的实例ResultSet,没有实现方法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

伦纳德理查森的注意事项:我绝不打算通过将其称为 BS 来贬低您的工作质量;-)

于 2009-06-14T06:17:16.113 回答