...">

Changing an element value with BeautifulSoup returns an 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 to change the contents of an element, in this case the element in the "make" variable, without losing the contents? If you can point me to other pure python modules that can modify existing xml documents, please let me know.

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

+3
source share
2 answers

View the documentation atreplaceWith . It works:

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

BeautifulSoup 4 (bs4), string :

from bs4 import BeautifulSoup

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

soup = BeautifulSoup(xml_data)
make = soup.find('foo:bar')

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

, , :

parent = soup.find('parent')
parent.string = 'Top of the world Ma!'

print parent
# prints <parent>Top of the world Ma!</parent>

, . , , , , , .

+2

Source: https://habr.com/ru/post/1705816/


All Articles