【问题标题】:Why am I getting "'ResultSet' has no attribute 'findAll'" using BeautifulSoup in Python?为什么我在 Python 中使用 BeautifulSoup 得到“'ResultSet' 没有属性 'findAll'”?
【发布时间】:2010-11-02 19:02:21
【问题描述】:

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

提前致谢。

【问题讨论】:

  • 为了它的价值:将变量命名为“first”、“second”等是糟糕的风格。你真的应该更具描述性——当然,具体的名称取决于你,但我可能会使用“urlcontent”、“parser”、“mp_tables”等等。
  • 这是我使用 Python 的第三天。我需要这样做以保持头脑清醒。随着时间的推移,情况会变得更好......
  • 我更改了变量名。希望那会更好。

标签: python urllib2 beautifulsoup


【解决方案1】:

哇。 Triptych 为相关问题提供了great answer

我们可以看到,from BeautifulSoup's source codeResultSetlist 的子类。

在您的示例中,get_rows 是 BS 的 ResultSet 类的一个实例,
并且由于 BS 的 ResultSetlist 的子类,这意味着 get_rows 是一个列表

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

Leonard Richardson 请注意:我绝不打算通过将其称为 BS 来贬低您的工作质量 ;-)

【讨论】:

  • text=True 正是我想要的!
猜你喜欢
  • 2013-06-20
  • 1970-01-01
  • 2016-12-19
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
相关资源
最近更新 更多