下面是执行所需 *** 作的示例。对于HTML文档,
Cleaner比使用更好的解决方法是使用
strip_elements,因为在这种情况下,您不仅要剥离
<script>标签,还应剥离更多标签。您还想摆脱
onclick=function()其他标签上的属性之类的东西。
#!/usr/bin/env pythonimport lxmlfrom lxml.html.clean import Cleanercleaner = Cleaner()cleaner.javascript = True # This is True because we want to activate the javascript filtercleaner.style = True # This is True because we want to activate the styles & stylesheet filterprint("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文档中获得可以设置的选项的列表;您可以将某些选项设置为
True或
False(默认),而其他选项则采用以下列表:
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).
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)