删除h2直到你到达beautifulsoup的下一个h2

时间:2016-11-05 23:15:49

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

考虑以下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时,我发现一个h2,其ID在我的列表中(ignore_list)我应该删除它下面的所有ul和lis,直到找到另一个h2。然后我会检查下一个h2是否在我的忽略列表中,如果是,删除所有的ul和lis直到我到达下一个h2(或者如果没有h2s,则删除当前的h2和lis并停止)。

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

以下是我正在尝试使用的完整HMTL:http://pastebin.com/Z3ev9c8N

我试图删除所有的UL和lis&#34; See_also&#34; 我将如何在Python中实现这一目标?

1 个答案:

答案 0 :(得分:0)

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

删除我不想要的内容

        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    
相关问题