2016-04-24 177 views
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 

我该如何纠正?

回答

2

的问题是,你正在重新定义元素的.string,而是我会找到“文本”节点并提出有更换:

for text in elm.find_all(text=True): 
    text.replace_with(text.replace("A", "X").replace("B", "Y").replace("C", "Z")) 

工作对我来说,生产:

</p> 
    <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';"> 
    XYZ XYZ 
    <br/> 
    XYZ 
    </span> 
</p> 

how can i include this part in a loop?

下面是一个示例:

replacements = { 
    "A": "X", 
    "B": "Y", 
    "C": "Z" 
} 
for text in elm.find_all(text=True): 
    text_to_replace = text 
    for k, v in replacements.items(): 
     text_to_replace = text_to_replace.replace(k, v) 

    text.replace_with(text_to_replace) 
+0

非常感谢你alecxe!但一个简单的问题是,我如何将这部分包含在循环中? 它提供了一个错误 文件“/ usr(”。“)。 /lib/python3/dist-packages/bs4/element.py“,第211行,在replace_with my_index = self.parent.index(self) AttributeError:'NoneType'对象没有属性'index' 再次感谢你! – PVGM

+0

很棒@alecxe !!非常感谢您的建议...... – PVGM