2016-03-18 34 views
0

我是一個(非常)新的Python用戶,並決定我的第一部作品是從論壇抓取一些歌詞並根據詞頻進行排序。我顯然還沒有進入頻率部分,但以下代碼不能用於獲取我想要的字符串值,導致「AttributeError:」ResultSet對象沒有屬性「getText」「:使用Python/bs4從論壇剝離HTML標籤

from bs4 import BeautifulSoup 
import urllib.request 

url = 'http://www.thefewgoodmen.com/thefgmforum/threads/gdr-marching-songs-section-b.14998' 
wp = urllib.request.urlopen(url) 
soup = BeautifulSoup(wp.read()) 
message = soup.findAll("div", {"class": "messageContent"}) 
words = message.getText() 
print(words) 

如果我改變了代碼,具有getText()soup對象進行操作:

words = soup.getText() 

我,當然,得到所有的字符串值的整個網頁,而不是那些僅限於類messageContent

因此,我的問題是雙重的: 1)是否有簡單的方法將標籤剝離限制爲僅限於預期的部分? 2)什麼簡單的東西我不明白,我不能有getText()message對象進行操作?

謝謝。

+0

根據[BeautifulSoup的文檔(http://www.crummy.com/software/BeautifulSoup/bs4/doc/)'的findAll()'返回'list'對象,所以你會需要像'for i in message:print i.getText()'那樣做一些事情。對不起,應用程序的格式。 –

+0

'findAll'返回元素列表,'getText()'只適用於字符串。嘗試打印出已分配給「message」的內容,並且可以更好地瞭解所發生的事情。 – bmcculley

回答

3

在這種情況下的message是BeautifulSoup ResultSet,這是BeautifulSoup Tag(多個)的列表。你需要做的是message像這樣每個元素調用getText

words = [item.getText() for item in message] 

同樣,如果你是在一個單一的Tag(比方說第一個爲參數的緣故)有興趣,你可以得到其內容有,

words = message[0].getText() 
+2

FWIW,BeautifulSoup切換到PEP8指南並更喜歡get_text()現在:-) – n1c9

+0

是。同樣,你應該使用'soup.find_all()'而不是'soup.findAll()'。 –