2017-08-18 7 views
1

私はこのようなファイルがあります:美味しいスープでタグの外のテキストを見つけたり変更したりするにはどうすればいいですか?

words1 outside of a Tag <tag1> words2 inside of tag1 </tag1> words3 outside of a Tag 

私はtag1の外の文字列を抽出し、beautifulsoupでこのような何かにそれを変更したい:私は、タグの外に言葉を置き換えることができますどのように

changed word1 <tag1> words2 inside of tag1 </tag1> changed word3 

を美しいスープ?

答えて

2

テキスト要素も親要素の子要素とみなされます。

tag1が見つかった場合は、属性.previousSibling.nextSiblingに前後のテキストがあります。または、親タグを見つけて、適切な子を選択することもできます。

例:

from bs4 import BeautifulSoup 
# assuming BeautifulSoup 4 

doc = """ 
words1 outside of a Tag <tag1>words2 inside of tag1</tag1> 
words3 outside of a Tag 
""" 

soup = BeautifulSoup(doc, 'html.parser') 
tag = soup.find('tag1') 
tag.previousSibling.replaceWith('changed word1 ') 
tag.nextSibling.replaceWith(' changed word3') 

print(soup) 
関連する問題