使用 BeautifulSoup 更改元素值返回空元素 [英] Changing element value with BeautifulSoup returns empty element

查看:21
本文介绍了使用 BeautifulSoup 更改元素值返回空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from BeautifulSoup import BeautifulStoneSoup

xml_data = """
<doc>
  <test>test</test>
  <foo:bar>Hello world!</foo:bar>
</doc>
"""

soup = BeautifulStoneSoup(xml_data)
print soup.prettify()
make = soup.find('foo:bar')
print make
# prints <foo:bar>Hello world!</foo:bar>

make.contents = ['Top of the world Ma!']
print make
# prints <foo:bar></foo:bar>

如何在不丢失内容的情况下更改元素的内容,在本例中是变量make"中的元素?如果您能指出其他可以修改现有 xml 文档的纯 python 模块,请告诉我.

How do I change the content of the element, in this case the element in the variable "make", without loosing the content? If you could point me to other pure python modules which can modify existing xml-documents, please let me know.

附上!BeautifulSoup 非常适合对 HTML 和 XML 进行屏幕抓取和解析!

PS! BeautifulSoup is great for screenscraping and parsing of both HTML and XML!

推荐答案

查看 关于 replaceWith 的文档.这有效:

Check out the documentation on replaceWith. This works:

make.contents[0].replaceWith('Top of the world Ma!')

这篇关于使用 BeautifulSoup 更改元素值返回空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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