【问题标题】:(python, beautifulsoup) When a 'td' contains certain string, take the whole tr(python, beautifulsoup) 当一个 'td' 包含某个字符串时,取整个 tr
【发布时间】:2021-06-15 04:24:57
【问题描述】:

我有一个包含多个 'tr' 的 html 代码,同时每个 'tr' 内部都有多个 'td' .我有兴趣只获取包含带有 ax 字符串的 'td' 的整个 'tr' 并且我希望代码过滤掉所有 'tr' 不包含带有该 x 字符串的 'td' 。 那可能吗?。我是新手,我花了几个小时寻找解决方案,但我做不到。

例如,我想获取包含字符串“acid blob”的'td'的整个'tr'

                                    <tr>
                                    <td>2</td>
                                    <td><b><a href="http://tibia.fandom.com/wiki/abyssal calamaries">abyssal calamaries</a></b></td>
                                    <td><img loading="lazy" src="images/monsters/abyssal_calamaries.gif" alt="abyssal calamaries"></td>
                                    <td>2020-05-28</td>
                                    <td>0</td>
                                    <td>0</td>
                                    <td>47246</td>
                                    <td>0</td>
                                    
                                 </tr><tr>
                                    <td>3</td>
                                    <td><b><a href="http://tibia.fandom.com/wiki/acid blobs">acid blobs</a></b></td>
                                    <td><img loading="lazy" src="images/monsters/acid_blobs.gif" alt="acid blobs"></td>
                                    <td>2020-05-28</td>
                                    <td>325</td>
                                    <td>0</td>
                                    <td>93153</td>
                                    <td>1</td>
                                    
                                 </tr><tr>
                                    <td>4</td>
                                    <td><b><a href="http://tibia.fandom.com/wiki/acolytes of darkness">acolytes of darkness</a></b></td>
                                    <td><img loading="lazy" src="images/monsters/acolytes_of_darkness.gif" alt="acolytes of darkness"></td>
                                    <td>2020-11-11</td>
                                    <td>0</td>
                                    <td>0</td>
                                    <td>4569</td>
                                    <td>0</td>

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    您可以找到td 标签并使用.find_parent('tr') 将备份移至tr 标签。

    .parent 也适用于此)

    >>> len([td.find_parent('tr') for td in soup.find_all('td', string='acid blobs')])
    1
    >>> len(soup.find_all('tr'))
    3
    

    https://beautiful-soup-4.readthedocs.io/en/latest/#going-up

    【讨论】:

    • 我是用 f​​ind_parent 函数做到的,谢谢你好先生
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多