【问题标题】:Delete h2 until you reach the next h2 in beautifulsoup删除 h2 直到到达 beautifulsoup 中的下一个 h2
【发布时间】:2016-11-05 23:15:49
【问题描述】:

考虑以下html:

<h2 id="example">cool stuff</h2> <ul> <li>hi</li> </ul> <div> <h2 id="cool"><h2> <ul><li>zz</li> </ul> </div>

以及以下列表:

ignore_list = ['example','lalala']

我的目标是,在使用 Beautifulsoup 浏览 HTML 时,我找到一个在我的列表 (ignore_list) 中有 ID 的 h2,我应该删除它下面的所有 ul 和 lis,直到找到另一个 h2。然后我会检查下一个 h2 是否在我的忽略列表中,如果是,删除所有 ul 和 lis 直到我到达下一个 h2 (或者如果没有 h2 剩下,删除当前一个下的 ul 和 lis 并停止)。

我如何看待这个过程:您在 DOM 中从上到下阅读了所有 h2。如果其中任何一个的 id 在 ignore_list 中,则删除 h2 下的所有 ul 和 li,直到到达 NEXT h2。如果没有h2,则删除ul和LI,然后停止。

这是我尝试使用的完整 HMTL:http://pastebin.com/Z3ev9c8N

我正在尝试删除“See_also”之后的所有 UL 和 lis 我将如何在 Python 中完成此任务?

【问题讨论】:

    标签: python html python-2.7 python-3.x beautifulsoup


    【解决方案1】:

    以下是我想出的解决方案。

    删除我不想要的内容

            try:
                for element in body.find_all('h2'):
                    current_h2 = element.get_text()
                    current_h2 = current_h2.replace('[edit]','')
                    #print(current_h2)
                    if(current_h2 in ignore_list):
                        if(element.find_next_sibling('div') != None):
                            element.find_next_sibling('div').decompose()
                        if(element.find_next_sibling('ul') != None):
                            element.find_next_sibling('ul').decompose()
            except(AttributeError, TypeError) as e:
                continue    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 2012-04-18
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2018-10-15
      • 2015-05-07
      相关资源
      最近更新 更多