Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

python - Changing element value with BeautifulSoup returns empty element

from BeautifulSoup import BeautifulStoneSoup

xml_data = """
<doc>
  <test>test</test>
  <foo:bar>Hello world!</foo:bar>
</doc>
"""

soup = BeautifulStoneSoup(xml_data)
print soup.prettify()
make = soup.find('foo:bar')
print make
# prints <foo:bar>Hello world!</foo:bar>

make.contents = ['Top of the world Ma!']
print make
# prints <foo:bar></foo:bar>

How do I change the content of the element, in this case the element in the variable "make", without loosing the content? If you could point me to other pure python modules which can modify existing xml-documents, please let me know.

PS! BeautifulSoup is great for screenscraping and parsing of both HTML and XML!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check out the documentation on replaceWith. This works:

make.contents[0].replaceWith('Top of the world Ma!')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...