如何删除标签<a> and <strike>?

时间:2018-12-12 11:14:30

标签: python beautifulsoup

I'd like to get the text of all p tags, removing all the content inside tags a and strike.

A piece of the html page:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

   <a href="Emendas/Emc/emc45.htm#art1">(Incluído pela Emenda Constitucional nº 45, de 2004)</a>
   <a href="../CONGRESSO/DLG/DLG-186-2008.htm">DLG nº 186, de 2008</a>
   <a href="../_Ato2007-2010/2009/Decreto/D6949.htm"><font size="2">DEC 6.949, 
    de 2009</font></a>
</p>
<p style="margin-top: 0; margin-bottom: 0"><strike>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium</strike></p> 

That's what I'm trying to do, but it's not working:

VALID_TAGS = ['a','strike']
for string in soup.body.descendants:
    if string.name not in VALID_TAGS:
      if isinstance(string, NavigableString):
        print (string)

The result expected:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

1 个答案:

答案 0 :(得分:2)

您可以尝试decompose()

html ='''
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

   <a href="Emendas/Emc/emc45.htm#art1">(Incluído pela Emenda Constitucional nº 45, de 2004)</a>
   <a href="../CONGRESSO/DLG/DLG-186-2008.htm">DLG nº 186, de 2008</a>
   <a href="../_Ato2007-2010/2009/Decreto/D6949.htm"><font size="2">DEC 6.949, 
    de 2009</font></a>
</p>
<p style="margin-top: 0; margin-bottom: 0"><strike>Lorem ipsum dolor sit amet, consectetur adipiscing elit, </strike></p>
'''

soup = BeautifulSoup(html, 'html.parser')

for p in soup.findAll('p'):
    for tag in p.findAll(True):
        if tag.name in ['a', 'strike']:
            tag.decompose()
    print(p.text.strip())