2017-01-02 89 views
0

我已經使用bs4在bs4中提取這個結果集。遍歷結果集bs4

<div> 
<div> 
</div> 
Content 1 
</div> 

<div> 
Content 2 
</div> 

我想提取這2個元素。

Moi not cute not hot, the ugly bui bui type 1Actually, moi also dun know

from bs4 import BeautifulSoup 
import urllib 
import re 
r = urllib.urlopen(
    'http://forums.hardwarezone.com.sg/eat-drink-man-woman-16/%5Bofficial%5D-chit-chat-students-part-2-a-5526993-55.html').read() 

soup = BeautifulSoup(r, "lxml") 
letters = soup.find_all("div", attrs={"id":re.compile("post_message_\d+")}) 

這裏是我的代碼。但是,如何遍歷結果集,以便它僅在關閉div之前提取內容方式。

letters.find_all('div')返回一個空集。

回答

0

所有消息:

from bs4 import BeautifulSoup 
import urllib 
import re 

r = urllib.urlopen(
    'http://forums.hardwarezone.com.sg/eat-drink-man-woman-16/%5Bofficial%5D-chit-chat-students-part-2-a-5526993-55.html').read() 

soup = BeautifulSoup(r, "lxml") 
letters = soup.find_all("div", attrs={"id":re.compile("post_message_\d+")}) 
for a in letters: 
    print [b.strip() for b in a.text.strip().split('\n') if b.strip()]