python : Replacing a HTML element depending on its content

标签 python html minidom

我有一个 html 文档,其中一些元素包含我想要隐藏的内容(就像中国政府正在做的那样,只不过我只是想隐藏 secret 信息)。例如说我有:

<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>

我考虑过将 minidomre 与以下内容一起使用:

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 或者完全不同的东西?

最佳答案

好的...我找到了一个非常简单的方法,使用 BeautifulSoup :

import re
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(my_html)
nodes_to_censor = soup.findAll(text=re.compile('.*SECRET.*'))
for node in nodes_to_censor:
    node.replaceWith('###')

关于 python : Replacing a HTML element depending on its content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5634522/

相关文章:

Python minidom 解析 xml 给出 None 或空字符串,而不是 xml 中的值

python - 热图中的标签组

javascript - 为什么表格在 IE 中的边框比 FireFox 中的边框大

python - Keras:重用多个层的权重

javascript - 如何运行远程 PHP 脚本,然后点击 HTML 页面中的链接

html - Box 不居中 css 布局

python - 对使用哪个 XML 处理选项感到困惑

python - 使用 minidom 获取节点名称

python - 扩展 Python 列表(例如 l += [1])是否保证是线程安全的?

python - 代码不适用于十位和百位的奇数