python:根据内容替换 HTML 元素
我有一个 html 文档,其中一些元素包含我想要隐藏的内容(就像中国政府正在做的那样,只不过我只是想隐藏机密信息)。例如,假设我有:
<div>
<span> bkhiu jknd o so so so yui iou 789 </span>
<span>
bkhiu
<div> 56 898tr SECRET oij890 </div>
</span>
</div>
并且我想获取包含字符串 SECRET
的所有元素,并用 ### 替换它们的整个内容:
<div>
<span> bkhiu jknd o so so so yui iou 789 </span>
<span>
bkhiu
<div>###</div>
</span>
</div>
我考虑过使用 minidom
> 和 re
类似:
xmldoc = minidom.parseString(my_html_string)
# filtering nodes by their content
sensitive_nodes = filter(lambda n: re.search('SECRET', n.nodeValue),
xmldoc.getElementsByTagName())
# replacing content
for node in sensitive_nodes:
node.nodeValue = '###'
# output
my_html_string = xmldoc.toxml()
但首先解析甚至没有成功:
ExpatError: mismatched tag: line 27, column 6
并且 .getElementsByTagName()
需要一个 tagName
参数...虽然我不关心标签名称并且需要所有节点(以便按其内容进行过滤)。基本上,该代码根本不起作用,只是试图解释我想要实现的目标。
知道我怎样才能轻松做到这一点吗?与 minidom 或完全不同的东西?
I have an html document, in which some elements contains stuff that I want to hide (like the Chinese government is doing, except that I just want to hide confidential information). For example say I have :
<div>
<span> bkhiu jknd o so so so yui iou 789 </span>
<span>
bkhiu
<div> 56 898tr SECRET oij890 </div>
</span>
</div>
And I want to get all the elements that contain the string SECRET
, and just replace their whole content by ### :
<div>
<span> bkhiu jknd o so so so yui iou 789 </span>
<span>
bkhiu
<div>###</div>
</span>
</div>
I have thought of using minidom
and re
with something like :
xmldoc = minidom.parseString(my_html_string)
# filtering nodes by their content
sensitive_nodes = filter(lambda n: re.search('SECRET', n.nodeValue),
xmldoc.getElementsByTagName())
# replacing content
for node in sensitive_nodes:
node.nodeValue = '###'
# output
my_html_string = xmldoc.toxml()
But first the parsing doesn't even succeeds :
ExpatError: mismatched tag: line 27, column 6
And .getElementsByTagName()
needs a tagName
parameter ... while I don't care about the tag name and need ALL the nodes (in order to filter by their content). Well basically that code doesn't work at all, but is just to try to explain what I wanna achieve.
Any idea how I could do that easily ? With minidom or something completely different ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的...我找到了一个非常简单的方法,使用 BeautifulSoup :
Ok ... I have found a very simple way, using BeautifulSoup :