栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

下面是执行所需操作的示例。对于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).


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648929.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号