使用python和BeautifulSoup从html中提取表内容

Isa*_*aac 8 python screen-scraping 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>
Run Code Online (Sandbox Code Playgroud)

我想提取信息,如"发布日期:".看起来像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
Run Code Online (Sandbox Code Playgroud)

这将获取第一个表行的内容,以及内容列表.但是下一个兄弟的事情是行不通的,我想我只是错了.当然我可以解析内容,但在我看来,美丽的汤旨在阻止我们这样做(如果我开始解析自己,我不妨解析整个文档......).如果有人能够告诉我如何实现这一点,我将感激不尽.如果有更好的方式然后BeautifulSoup,我会有兴趣听到它.

fal*_*tru 19

>>> 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'
Run Code Online (Sandbox Code Playgroud)