2013-08-01 18 views
0

我得到一個網站的文字文章在pythonBeatifulSoup的幫助下。現在我有一個奇怪的問題......我只是打印出多個p標籤中的文本,這些標籤位於dr_article類的div中。現在的代碼看起來像這樣:Python和美麗的湯,拿起所有元素

from bs4 import BeautifulSoup 

def getArticleText(webtext): 
soup = BeautifulSoup(webtext) 
divTag = soup.find_all("div", {"class":"dr_article"}) 
for tag in divTag: 
    pData = tag.find_all("p").text 
    print pData 

我收到以下錯誤:

Traceback (most recent call last): 
    File "<pyshell#14>", line 1, in <module> 
execfile("word_rank/main.py") 
    File "word_rank/main.py", line 7, in <module> 
articletext.getArticleText(webtext) 
    File "word_rank\articletext.py", line 7, in getArticleText 
pData = tag.find_all("p").text 
AttributeError: 'list' object has no attribute 'text' 

但是,當我.text之前只選擇與[0]的第一個元素我沒有收到錯誤,它按照應該的方式工作。它獲取第一個元素文本。準確地說我修改我的代碼,它看起來像這樣:

from bs4 import BeautifulSoup 

def getArticleText(webtext): 
soup = BeautifulSoup(webtext) 
divTag = soup.find_all("div", {"class":"dr_article"}) 
for tag in divTag: 
    pData = tag.find_all("p")[0].text 
    print pData 

我的問題是我怎麼能同時得到所有元素的文字?要修改什麼,所以我不會只從一個元素獲取文本,而是從所有元素獲取文本?

+0

你有沒有嘗試* *循環比'.find_all( 'P')'的結果呢? –

回答

1

您正在獲取所有元素,所以函數返回列表。試着通過它去:

from bs4 import BeautifulSoup 

def getArticleText(webtext): 
soup = BeautifulSoup(webtext) 
divTag = soup.find_all("div", {"class":"dr_article"}) 
for tag in divTag: 
    for element in tag.find_all("p"): 
     pData = element.text 
     print pData 

或者您也可以單獨選擇每一個元素:

tag.find_all("p")[0].text 
tag.find_all("p")[1].text 
tag.find_all("p")[..].text 
tag.find_all("p")[N - 1].text 
tag.find_all("p")[N].text 
+0

我已經成功地用pData中的for循環標記工作,然後將.text添加到標記中。但你的例子比較短,我會用那個......謝謝:) – dzordz