BeautifulSoup4:更改xml标记内的文本

时间:2017-01-08 21:08:26

标签: python xml beautifulsoup

我只想在xml标记成为BeautifulSoup对象后更改其内部的文本。

当前代码:

Chart

在我的控制台中运行此代码会出现此错误:

example_string = '<conversion><person>John</person></conversion>'
bsoup = BeautifulSoup(example_string)
bsoup.person.text = 'Michael'

如何更改Traceback (most recent call last): File "<stdin>", line 3, in <module> AttributeError: can't set attribute xml标记内的值?

1 个答案:

答案 0 :(得分:2)

您需要设置.string attribute,而不是.text,它是只读的:

example_string = '<conversion><person>John</person></conversion>'
bsoup = BeautifulSoup(example_string, "xml")
bsoup.person.string = 'Michael'

演示:

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>