简体   繁体   English

美丽的汤和表

[英]Beautiful Soup and Tables

Hi I'm trying to parse an html table using Beautiful Soup. 嗨,我正在尝试使用Beautiful Soup解析html表。 The table looks something like this: 该表看起来像这样:

<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>

I would like to get the information from the second table, and so far I tried this code: 我想从第二个表中获取信息,到目前为止我尝试了这段代码:

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

That doesnt seem to work, any help would be much appreciated, Thanks 这似乎不起作用,任何帮助将不胜感激,谢谢

The first problem is with this statement: "t=soup.find(id='table')" There is nothing with an id of table. 第一个问题是这句话:“t = soup.find(id ='table')”没有任何表的id。 I think what you mean is "t=soup.find('table')" this finds a table. 我想你的意思是“t = soup.find('table')”这找到了一张桌子。 Unfortunately it only finds the first table. 不幸的是,它只找到第一个表。

You could do "t=soup.findAll(table)[1]" but this would be quite brittle. 你可以做“t = soup.findAll(table)[1]”,但这会非常脆弱。

I would suggest something like the following: 我建议如下:

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') )

The resulting dat variable is: 生成的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>']]

Edit: wrong array index 编辑:错误的数组索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM