BeautifulSoup4:更改xml标记内的文本 [英] BeautifulSoup4: change text inside xml tag

查看:303
本文介绍了BeautifulSoup4:更改xml标记内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在xml标记变成BeautifulSoup对象之后更改其中的文本.

I simply want to change the text inside an xml tag after it becomes a BeautifulSoup object.

当前代码:

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

如何更改person xml标记内的值?

How can I change the value inside the person xml tag?

推荐答案

您需要设置 .string属性,而不是只读的.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>

这篇关于BeautifulSoup4:更改xml标记内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆