【问题标题】:Using Beautiful Soup to strip html tags from a string使用 Beautiful Soup 从字符串中去除 html 标签
【发布时间】:2011-05-24 08:42:48
【问题描述】:

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

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

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

还有类似的东西:

<a onclick=""></a>

感谢您的帮助 -- 为此我在互联网上找不到太多信息。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:
    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>
    

    如果你只想要文本内容,你可以将print(tag)更改为print(tag.string)

    如果您想从a 标记中删除像onclick="" 这样的属性,您可以这样做:

    if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
        if tag.name=='a':
            del tag['onclick']
        print(tag)
    

    【讨论】:

    • 谢谢 -- 任何删除 onclick="" 的方法
    • 在打印前添加 'tag.attrs=[]' 以删除所有属性。如果您需要更多控制,tag.attrs 只是您可以根据需要使用的(名称,值)对的列表。
    猜你喜欢
    • 2018-01-17
    • 2019-02-20
    • 2014-11-16
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多