使用python和lxml模块从html删除所有javascript标签和样式标签

发布于 2021-01-29 15:09:24

我正在使用http://lxml.de/库解析html文档。到目前为止,我已经弄清楚了如何从html文档中剥离标签。在lxml中,如何删除标签但保留所有内容?但是该文章中描述的方法将保留所有文本,剥离标签而不会删除实际脚本。我还找到了一个对lxml.html.clean.Cleaner的类引用http://lxml.de/api/lxml.html.clean.Cleaner-
class.html,
但这对于如何实际使用该类很明显清洁文档。任何帮助,也许是一个简短的例子对我都会有所帮助!

关注者
0
被浏览
78
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    下面是执行所需操作的示例。对于HTML文档,Cleaner比使用更好的解决方法是使用strip_elements,因为在这种情况下,您不仅要剥离<script>标签,还应剥离更多标签。您还想摆脱onclick=function()其他标签上的属性之类的东西。

    #!/usr/bin/env python
    
    import lxml
    from lxml.html.clean import Cleaner
    
    cleaner = Cleaner()
    cleaner.javascript = True # This is True because we want to activate the javascript filter
    cleaner.style = True      # This is True because we want to activate the styles & stylesheet filter
    
    print("WITH JAVASCRIPT & STYLES")
    print(lxml.html.tostring(lxml.html.parse('http://www.google.com')))
    print("WITHOUT JAVASCRIPT & STYLES")
    print(lxml.html.tostring(cleaner.clean_html(lxml.html.parse('http://www.google.com'))))
    

    您可以在lxml.html.clean.Cleaner文档中获得可以设置的选项的列表;您可以将某些选项设置为TrueFalse(默认),而其他选项则采用以下列表:

    cleaner.kill_tags = ['a', 'h1']
    cleaner.remove_tags = ['p']
    

    注意kill和remove之间的区别:

    remove_tags:
      A list of tags to remove. Only the tags will be removed, their content will get pulled up into the parent tag.
    kill_tags:
      A list of tags to kill. Killing also removes the tag's content, i.e. the whole subtree, not just the tag itself.
    allow_tags:
      A list of tags to include (default include all).
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看