2012-11-02 140 views
24

孩子我都在嘗試解析網頁看起來像這樣與Python->美麗的湯:enter image description here美麗的湯找到特定的div

我試圖提取強調TD div的內容。目前,我可以通過

alltd = soup.findAll('td') 


for td in alltd: 
    print td 

得到所有的div但我試圖縮小的範圍來搜索類「tablebox」仍可能會回到30+,但更易於管理的數字大於300 TDS +。

如何提取上圖中突出顯示的td的內容?

回答

42

知道BeautifulSoup在一個元素中發現的任何元素仍然具有與該父元素相同的類型是很有用的 - 也就是說,可以調用各種方法。

因此,這是你的榜樣有些工作代碼:

soup = BeautifulSoup(html) 
divTag = soup.find_all("div", {"class": "tablebox"}): 

for tag in divTag: 
    tdTags = tag.find_all("td", {"class": "align-right"}) 
    for tag in tdTags: 
     print tag.text 

這將打印所有TD標籤的所有文本與類的「對齊右」有父DIV與類的「tablebox」。

+1

在父循環中,標籤是'div'元素而不是湯元素,所以我認爲它會產生錯誤,不是嗎?在'div'元素中,它沒有名爲'find_all'的方法 – LKM