【问题标题】:BeautifulSoup4: change text inside xml tagBeautifulSoup4:更改 xml 标签内的文本
【发布时间】:2017-05-23 02:50:30
【问题描述】:

我只是想在 xml 标记内的文本变成 BeautifulSoup 对象后对其进行更改。

当前代码:

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

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

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    您需要设置.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>
    

    【讨论】:

      猜你喜欢
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      相关资源
      最近更新 更多