BeautifulSoup4: change text inside xml tag

≡放荡痞女 提交于 2019-12-23 05:39:17

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/41537926/beautifulsoup4-change-text-inside-xml-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!