1
我使用bs4来操纵一些富文本。但它在我做角色转换的地方删除了br标签。下面是代码的简单形式。Python bs4删除br标签
import re
from bs4 import BeautifulSoup
#source_code = self.textInput.toHtml()
source_code = """.......<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">ABC ABC<br />ABC</span></p>......."""
soup = BeautifulSoup(source_code, "lxml")
for elm in soup.find_all('span', style=re.compile(r"font-family:'Ubuntu'")):
#actually there was a for loop
elm.string = elm.text.replace("A", "X")
elm.string = elm.text.replace("B", "Y")
elm.string = elm.text.replace("C", "Z")
print(soup.prettify())
这应该给一个输出
...<span style=" font-family:'Ubuntu';">XYZ XYZ<br />XYZ</span>...
#XYZ XYZ
#XYZ
但它给输出,而不BR标签。
...<span style=" font-family:'Ubuntu';">XYZ XYZXYZ</span>...
#XYZ XYZXYZ
我该如何纠正?
非常感谢你alecxe!但一个简单的问题是,我如何将这部分包含在循环中? 它提供了一个错误 文件“/ usr(”。“)。 /lib/python3/dist-packages/bs4/element.py“,第211行,在replace_with my_index = self.parent.index(self) AttributeError:'NoneType'对象没有属性'index' 再次感谢你! – PVGM
很棒@alecxe !!非常感谢您的建议...... – PVGM