2017-05-04 101 views
0

使用BeautifulSoup,我從所述頁面的html文檔中提取了網頁上的評論。使用此代碼我已經能夠打印出意見:從HTML文檔中提取文本到單詞列表中

import urllib2 
 
from bs4 import BeautifulSoup 
 

 
url = "http://songmeanings.com/songs/view/3530822107858560012/" 
 
response = urllib2.build_opener(urllib2.HTTPCookieProcessor).open(url) 
 
html_doc = response.read() 
 
soup = BeautifulSoup(html_doc, 'html.parser') 
 

 
def loop_until(text,first_elem): 
 
    try: 
 
    text += first_elem.string 
 
    if first_elem.next == first_elem.find_next('div'): 
 
     return text 
 
    else: 
 
     return loop_until(text,first_elem.next.next) 
 
    except TypeError: 
 
     pass 
 
     
 
wordList = [] 
 

 
for strong_tag in soup.find_all('strong'): 
 
    next_elem = strong_tag.next_sibling 
 
    print loop_until("", next_elem)

現在我需要從該選擇所有的字,並將其添加到單詞表,我將如何去這樣做?

回答

1

改變你的最後一行,使用append

wordList.append(loop_until("", next_elem)) 
+0

笑!我不知道爲什麼這並沒有超出我的想法。謝謝! –