2009-06-14 35 views
8

因此,我正在慢慢学习Python,并试图制作一个简单的函数,它将从网络游戏的高分页面中绘制数据。这是别人的代码,我重写了一个函数(这可能是问题),但我得到这个错误。这里是代码:为什么我在Python中使用BeautifulSoup时,'ResultSet'没有属性'findAll'“?

>>> 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' 

在此先感谢。

+0

它的价值:命名变量“第一”,“第二”等是可怕的风格。你真的应该更具描述性 - 当然,具体名称取决于你,但我可能会使用“urlcontent”,“parser”,“mp_tables”等。 – 2009-06-14 05:09:43

+0

它是我第三天与Python。我需要做到这一点,以保持我的头脑。随着时间的推移,这会变得更好...... – Alex 2009-06-14 05:12:33

回答

19

哇。三联画提供了一个great answer到一个相关的问题。

我们可以看到,from BeautifulSoup's source code,即ResultSet小类list

在你的榜样,get_rows是BS的ResultSet类的一个实例,
和自BS的ResultSetlist,这意味着get_rows是一个列表

get_rows,作为ResultSet的情况下,确实有实现的方法findAll;因此你的错误。
什么三联做了不同的是遍历该列表迭代
三联的方法是可行的,因为get_rows列表中的项目是BS的标记类的实例;其中有一个findAll方法。

所以,要解决你的代码,你可以用这样的替换最后三行您create方法:

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

注伦纳德·理查森:不能这样做,我打算贬低的质量你的工作通过称为BS ;-)

相关问题