2013-06-19 704 views
6

我想从html文档中提取某些信息。例如。它包含了一个表 像这样(与其他内容的其他表中):用python和BeautifulSoup从html中提取表格内容

<table class="details"> 
      <tr> 
        <th>Advisory:</th> 
        <td>RHBA-2013:0947-1</td> 
      </tr> 
      <tr>  
        <th>Type:</th> 
        <td>Bug Fix Advisory</td> 
      </tr> 
      <tr> 
        <th>Severity:</th> 
        <td>N/A</td> 
      </tr> 
      <tr>  
        <th>Issued on:</th> 
        <td>2013-06-13</td> 
      </tr> 
      <tr>  
        <th>Last updated on:</th> 
        <td>2013-06-13</td> 
      </tr> 

      <tr> 
        <th valign="top">Affected Products:</th> 
        <td><a href="#Red Hat Enterprise Linux ELS (v. 4)">Red Hat Enterprise Linux ELS (v. 4)</a></td> 
      </tr> 


    </table> 

我想提取喜欢的日期信息发布的“关于”。它看起来像BeautifulSoup4 可以做到这一点很容易,但不知何故,我没有设法让它正确。 到目前为止我的代码:

from bs4 import BeautifulSoup 
    soup=BeautifulSoup(unicodestring_containing_the_entire_htlm_doc) 
    table_tag=soup.table 
    if table_tag['class'] == ['details']: 
      print table_tag.tr.th.get_text() + " " + table_tag.tr.td.get_text() 
      a=table_tag.next_sibling 
      print unicode(a) 
      print table_tag.contents 

这让我第一个表行的内容,也是内容的列表。 但是,下一个兄弟姐妹的事情是不正确的,我想我只是用它错了。 当然,我可以解析内容thingy,但在我看来,美丽的汤 旨在阻止我们做到这一点(如果我开始解析自己,我可能 很好地解析了整个文档...)。如果有人能够启发我如何去实现这一点,我会很乐意。如果有更好的方法,那么BeautifulSoup,我会有兴趣 听说它。

回答

13
>>> from bs4 import BeautifulSoup 
>>> soup = BeautifulSoup(unicodestring_containing_the_entire_htlm_doc) 
>>> table = soup.find('table', {'class': 'details'}) 
>>> th = table.find('th', text='Issued on:') 
>>> th 
<th>Issued on:</th> 
>>> td = th.findNext('td') 
>>> td 
<td>2013-06-13</td> 
>>> td.text 
u'2013-06-13' 
相关问题