【问题标题】:how to parse table inside table using beautiful soup?如何使用漂亮的汤解析表中的表?
【发布时间】:2010-11-12 11:52:03
【问题描述】:

我试过这个: s = soup.findAll("table", {"class": "view"}) 但它给了我桌子。但我需要表中的表。

<table class="view" >
    <tr>
        <td width="46%" valign="top">
        <table>
    <tr>
        <td>
            <div style="adasdasd">
                <div class="abc">dasdsadasdasdas</div>
            </div>
            <div>
                <span><span class="aaaaaaa " title="aaaaaaaaaaa"><span>aaaaaaaaaaaaa</span></span> </span>
                <b>My Face</b><br />
                    Hello This is me,
                </div>
            <div class="abc"">
                    Dec 6, 2010 by Alis
                </div>
        </td>
    </tr>
        </table>
    </tr>
    </table>

The things I want to scrap is:

    Hello This is me,

    My Face

    Dec 6, 2010 by Alis

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:
    s = soup.findAll("table", {"class": "view"})[0].find("table")
    

    如果只有一个表,您也可以将.find 用于第一个表,并删除[0]

    【讨论】:

    • 'ResultSet' 对象没有属性 'find' - 我得到属性错误。
    • 如果你使用 findAll,你也需要 [0]。 findAll 为您提供了一个 ResultSet(如列表),因此您需要指定要使用找到的第一个。如果它只是在页面上找到了一个表,你可以使用 find 而不是 findAll 来获取它。
    【解决方案2】:

    这里有一些格式更好的html:

    <table class="view" >
        <tr>
            <td width="46%" valign="top">
                <table>
                    <tr>
                        <td>
                            <div style="adasdasd">
                                <div class="abc">dasdsadasdasdas</div>
                            </div>
                            <div>
                                <span>
                                    <span class="aaaaaaa " title="aaaaaaaaaaa">
                                        <span>aaaaaaaaaaaaa</span>
                                    </span>
                                </span>
                                <b>My Face</b>
                                <br />
                                Hello This is me,
                            </div>
                            <div class="abc">
                                Dec 6, 2010 by Alis
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    

    注意:我实际上添加了一个标签,因为它缺少一个。

    innerTable = soup.find("table", {"class": "view"}).tr.td.table ##Gets the table in the first cell of the first row
    
    innerDiv = innerTable.find("div", {"style": "adasdasd"}).nextSibling #this gets the div in which all of you content resides
    

    这样您就可以找到包含所有内容的内容。从那里只需进行一点解析即可获得您实际需要的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2021-03-06
      • 2019-11-10
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多