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

查看:234
本文介绍了与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>

如何更改该元素的含量,在这种情况下,在变量制造的元件,没有松动的内容?如果你能指出我的其它纯Python模块至极可以修改现有的XML的文档,请让我知道。

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 wich can modify existing xml-documents, please let me know.

PS! BeautifulSoup是伟大的屏幕抓取和HTML和XML解析!

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

推荐答案

查看<一个href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html#Replacing%20one%20Element%20with%20Another\">documentation在 replaceWith 。这工作:

Check out the documentation on replaceWith. This works:

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

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

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