【发布时间】:2020-08-14 20:15:49
【问题描述】:
我需要在 html 文件中找到某些单词并用链接替换它们。结果应该是该文件(由浏览器显示)允许您像往常一样单击链接。 Beautiful Soup 会自动转义标签。我怎样才能避免这种行为?
最小的例子
#!/usr/bin/env python3
from bs4 import BeautifulSoup
import re
html = \
'''
Identify
'''
soup = BeautifulSoup(html,features="html.parser")
for txt in soup.findAll(text=True):
if re.search('identi',txt,re.I) and txt.parent.name != 'a':
newtext = re.sub('identify', '<a href="test.html"> test </a>', txt.lower())
txt.replace_with(newtext)
print(soup)
结果:
<a href="test.html"> test </a>
预期结果:
<a href="test.html"> test </a>
【问题讨论】:
标签: python beautifulsoup replacewith