2016-04-24 3 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 

これを修正するにはどうすればよいですか? 、

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

私の作品生成します:

答えて

2

問題は、要素の.string再定義されているが、代わりに、私は「テキスト」ノードを見つけるだろうし、そこの交換をしたということです

</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

ありがとうございました! 1つの簡単な質問ですが、どのようにこの部分をループに含めることができますか? text.replace_with( "A"、 "X")replace( " /lib/python3/dist-packages/bs4/element.py "、行211、replace_with my_index = self.parent.index(self) AttributeError: 'NoneType'オブジェクトには属性 'index'がありません もう一度ありがとう! – PVGM

+0

great @alecxe !!アドバイスをいただきありがとうございます... – PVGM

関連する問題