用 BeautifulSoup 中的另一个标签替换一个标签 [英] Replace a tag with another tag in BeautifulSoup

查看:47
本文介绍了用 BeautifulSoup 中的另一个标签替换一个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 XML 文档中找到一个标签,并用一个新标签完全替换它.我有我认为应该在下面工作的内容:

I'm attempting to find a tag within an XML document, and replace it entirely with a new tag. I've got what I think should work below:

para = monograph.find('para', text='Some text.')
newpara = '<para>Some <emph type="bold">new</emph> text.</para>'
newpara = BeautifulSoup(newpara, 'xml')
para.replaceWith(newpara)

不幸的是,当我运行这个时,我得到:

Unfortunately, when I run this, I'm getting:

Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python34\lib\site-packages\bs4\element.py", line 211, in replace_with
my_index = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'

有什么建议吗?

推荐答案

您可以使用 replaceWith() 来实现这一点,这是一种方法:

You can use replaceWith() to achieve this, here is one way how to do it:

In [8]: from bs4 import BeautifulSoup

In [9]: tree = BeautifulSoup('<html><body><div>Foo</div><div>Bar</div><para>Some text.</para></body></html>', 'xml')

In [10]: newpara = '<para>Some <emph type="bold">new</emph> text.</para>'

In [11]: newpara = BeautifulSoup(newpara, 'xml')

# here I use newpara.para as a shortcut to get the <para> element
# as a new BeautifulSoup will include wrapping tags
In [12]: tree.find('para', text='Some text.').replaceWith(newpara.para)
Out[12]: <para>Some text.</para>

In [13]: print tree
<?xml version="1.0" encoding="utf-8"?>
<html><body><div>Foo</div><div>Bar</div><para>Some <emph type="bold">new</emph> text.</para></body></html>

希望这会有所帮助.

这篇关于用 BeautifulSoup 中的另一个标签替换一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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