2011-09-08 80 views
4

嗨我想解析一個HTML表使用美麗的湯。 表看起來是這樣的:美麗的湯和桌

<table width=100% border=1 cellpadding=0 cellspacing=0 bgcolor=#e0e0cc> 
<tr> 
    <td width=12% height=1 align=center valign=middle bgcolor=#e0e0cc bordercolorlight=#000000 bordercolordark=white> <b><font face="Verdana" size=1><a href="http://www.dailystocks.com/" alt="DailyStocks.com" title="Home">Home</a></font></b></td> 
</tr> 
</table> 
<table width="100%" border="0" cellpadding="1" cellspacing="1"> 
    <tr class="odd"><td class="left"><a href="whatever">ABX</a></td><td class="left">Barrick Gold Corp.</td><td>55.95</td><td>55.18</td><td class="up">+0.70</td><td>11040601</td><td>70.28%</td><td><center>&nbsp;<a href="whatever" class="bcQLink">&nbsp;Q&nbsp;</a>&nbsp;<a href="chart.asp?sym=ABX&code=XDAILY" class="bcQLink">&nbsp;C&nbsp;</a>&nbsp;<a href="texpert.asp?sym=ABX&code=XDAILY" class="bcQLink">&nbsp;O&nbsp;</a>&nbsp;</center></td></tr> 
</table> 

我想獲得第二個表中的信息,到目前爲止,我想這樣的代碼:

html = file("whatever.html") 
soup = BeautifulSoup(html) 
t = soup.find(id='table') 
dat = [ map(str, row.findAll("td")) for row in t.findAll("tr") ] 

這似乎沒有工作,任何幫助將不勝感激, 謝謝

回答

8

第一個問題是這個聲明:「t = soup.find(id ='table')」沒有什麼與表的id。我認爲你的意思是「t = soup.find('table')」這找到了一張桌子。不幸的是,它只發現第一個表。你可以做「t = soup.findAll(table)[1]」,但這會很脆弱。

我建議像下面這樣:

html = file("whatever.html") 
soup = BeautifulSoup(html) 
rows = soup.findAll("tr", {'class': ['odd', 'even']}) 
dat = [] 
for row in rows: 
    dat.append(map(str, row.findAll('td')) 

產生的DAT變量是:

[['<td class="left"><a href="whatever">ABX</a></td>', '<td class="left">Barrick Gold Corp.</td>', '<td>55.95</td>', '<td>55.18</td>', '<td class="up">+0.70</td>', '<td>11040601</td>', '<td>70.28%</td>', '<td><center>&nbsp;<a href="whatever" class="bcQLink">&nbsp;Q&nbsp;</a>&nbsp;<a href="chart.asp?sym=ABX&amp;code=XDAILY" class="bcQLink">&nbsp;C&nbsp;</a>&nbsp;<a href="texpert.asp?sym=ABX&amp;code=XDAILY" class="bcQLink">&nbsp;O&nbsp;</a>&nbsp;</center></td>']] 

編輯:錯誤的數組索引