美丽的汤和表格
你好,我正在尝试用Beautiful Soup来解析一个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> <a href="whatever" class="bcQLink"> Q </a> <a href="chart.asp?sym=ABX&code=XDAILY" class="bcQLink"> C </a> <a href="texpert.asp?sym=ABX&code=XDAILY" class="bcQLink"> O </a> </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") ]
但是这似乎不太管用,任何帮助都会非常感谢,谢谢!
1 个回答
8
第一个问题出在这句话上:“t=soup.find(id='table')”。这里并没有一个id为table的东西。我想你想表达的是“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> <a href="whatever" class="bcQLink"> Q </a> <a href="chart.asp?sym=ABX&code=XDAILY" class="bcQLink"> C </a> <a href="texpert.asp?sym=ABX&code=XDAILY" class="bcQLink"> O </a> </center></td>']]
补充:数组索引错误