Python-搜索并替换HTML中的破碎文本

时间:2018-07-19 02:46:40

标签: python html regex beautifulsoup

我一直在使用工具将pdf文档转换为HTML,以便可以更轻松地编辑它们,同时保留尽可能多的格式。我需要做的是将某些短语替换为文本“ [已删除]”,问题是该文本被随机标签(主要是跨度标签)意外地破坏了,所以我不能轻易地使用查找和替换。

作为示例,我需要从此html代码段中替换文本“要删除的敏感信息”:

<span class="fs4 fc2">Sensitive<span class="_ _b"> </span>Information to Re<span class="_ _c"></span>move</span>

与此:

<span class="fs4 fc2">[REDACTED]</span>

是否可以使用Beautiful Soup之类的库或某种复杂的正则表达式字符串来实现此目的?

1 个答案:

答案 0 :(得分:0)

要替换HTML文档中的文本,可以使用BeautifulSoup提供的clear()append()方法(manual pages):

data = """<span class="fs4 fc2">Sensitive<span class="_ _b"> </span>Information to Re<span class="_ _c"></span>move</span>"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

secret_string = "Sensitive Information to Remove"
redacted_string = "[REDACTED]"

while True:
    s = soup.body.find(lambda t: t.text==secret_string)
    if not s:
        break

    s.clear()
    s.append(redacted_string)

print(soup)

这将打印:

<html><body><span class="fs4 fc2">[REDACTED]</span></body></html>