Python 使用Beauty Soup从字符串中剥离html标记

Python 使用Beauty Soup从字符串中剥离html标记,python,beautifulsoup,Python,Beautifulsoup,有没有人有一些示例代码来说明如何使用Python的Beautiful Soup从文本字符串中除去所有html标记(除了一些标记) 我想去掉所有javascript和html标记,除了: <a></a> <b></b> <i></i> 还包括: <a onclick=""></a> 感谢您的帮助--我在internet上找不到太多用于此目的的内容。谢谢您--在打印之前删除onclick=“”

有没有人有一些示例代码来说明如何使用Python的Beautiful Soup从文本字符串中除去所有html标记(除了一些标记)

我想去掉所有javascript和html标记,除了:

<a></a>
<b></b>
<i></i>

还包括:

<a onclick=""></a>


感谢您的帮助--我在internet上找不到太多用于此目的的内容。

谢谢您--在打印之前删除onclick=“”add”tag.attrs=[]”以删除所有属性。如果您需要更多的控制,tag.attrs只是一个(名称、值)对的列表,您可以根据需要使用它。
import BeautifulSoup

doc = '''<html><head><title>Page title</title></head><body><p id="firstpara" align="center">This is <i>paragraph</i> <a onclick="">one</a>.<p id="secondpara" align="blah">This is <i>paragraph</i> <b>two</b>.</html>'''
soup = BeautifulSoup.BeautifulSoup(doc)

for tag in soup.recursiveChildGenerator():
    if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
        print(tag)
<i>paragraph</i>
<a onclick="">one</a>
<i>paragraph</i>
<b>two</b>
if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
    if tag.name=='a':
        del tag['onclick']
    print(tag)