从 HTML 中移除带有 style 属性的 span/div

偶尔我需要清理一些 HTML 代码 - 主要是因为其中部分内容是从 Word 等富文本编辑器粘贴到 Wordpress 等 CMS 中的。

我注意到我要删除的格式主要基于带有 style 属性的 spandiv 元素。因此,我编写了一个基于 BeautifulSoup4 的简单 Python 脚本,如果某些标签具有 style 属性,它将用其内容替换这些标签。虽然在某些情况下此类脚本可能会破坏其他格式,但它对于某些经常出现的用例非常有用。

removeformat_usage.sh
python3 removeformat.py input.html output.html
removeformat.py
#!/usr/bin/env python3
"""
在 HTML 文件中用其内容替换带有 style 属性的 span
"""
from bs4 import BeautifulSoup

__author__ = "Uli Köhler"
__copyright__ = "Copyright 2017 Uli Köhler"
__license__ = "CC0 1.0 Universal"
__version__ = "1.0"
__email__ = "ukoehler@techoverflow.net"


def modify_html(infile, outfile, tags):
    # 加载 HTML
    with open(infile, "r") as infile:
        soup = BeautifulSoup(infile, "html.parser")

    # 用其内容替换所有 span
    # 仅当它们有某种 style 属性时
    for tagtype in tags: # span, div etc
        for span in soup.find_all(tagtype):
            if "style" in span.attrs:
                span.replaceWithChildren()

    # 写入输出文件
    with open(outfile, "w") as outfile:
        outfile.write(soup.prettify())

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', help='要从中读取 HTML 的文件')
    parser.add_argument('outfile', help='要将结果 HTML 写入的文件')
    parser.add_argument('-t', '--tag', nargs='+', default=["span"], help='要检查和替换哪些标签类型')
    args = parser.parse_args()
    # 运行修改器
    modify_html(args.infile, args.outfile, args.tag)

Check out similar posts by category: Python