【发布时间】:2020-08-15 18:29:48
【问题描述】:
我需要替换 html 文档中的多个单词。 Atm 我通过为每次替换调用一次 replace_with 来做到这一点。在 NavigableString 上调用 replace_with 两次会导致 ValueError(参见下面的示例),导致被替换的元素不再在树中。
小例子
#!/usr/bin/env python3
from bs4 import BeautifulSoup
import re
def test1():
html = \
'''
Identify
'''
soup = BeautifulSoup(html,features="html.parser")
for txt in soup.findAll(text=True):
if re.search('identify',txt,re.I) and txt.parent.name != 'a':
newtext = re.sub('identify', '<a href="test.html"> test </a>', txt.lower())
txt.replace_with(BeautifulSoup(newtext, features="html.parser"))
txt.replace_with(BeautifulSoup(newtext, features="html.parser"))
# I called it twice here to make the code as small as possible.
# Usually it would be a different newtext ..
# which was created using the replaced txt looking for a different word to replace.
return soup
print(test1())
预期结果:
The txt is == newstring
结果:
ValueError: Cannot replace one element with another when the element to be replaced is not
part of the tree.
一个简单的解决方案就是修补新字符串,最后只一次全部替换,但我想了解当前的现象。
【问题讨论】:
标签: python beautifulsoup replacewith