2009-06-14 40 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 ;-)

相關問題