Reputation: 677
I simply want to change the text inside an xml tag after it becomes a BeautifulSoup object.
Current code:
example_string = '<conversion><person>John</person></conversion>'
bsoup = BeautifulSoup(example_string)
bsoup.person.text = 'Michael'
running this code in my console renders this error:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AttributeError: can't set attribute
How can I change the value inside the person
xml tag?
Upvotes: 2
Views: 5528
Reputation: 474271
You need to set the .string
attribute, not .text
which is read-only:
example_string = '<conversion><person>John</person></conversion>'
bsoup = BeautifulSoup(example_string, "xml")
bsoup.person.string = 'Michael'
Demo:
In [1]: from bs4 import BeautifulSoup
...:
...:
...: example_string = '<conversion><person>John</person></conversion>'
...: bsoup = BeautifulSoup(example_string, "xml")
...: bsoup.person.string = 'Michael'
...:
...: print(bsoup.prettify())
...:
<?xml version="1.0" encoding="utf-8"?>
<conversion>
<person>
Michael
</person>
</conversion>
Upvotes: 3