在 BeautifulSoup 中将一个标签替换为另一个标签

2023-12-14

我试图在 XML 文档中查找标签,并用新标签完全替换它。我认为下面应该有效:

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

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

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'

有什么建议吗?


您可以使用用。。。来代替()为了实现这一目标,这是一种方法:

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>

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 BeautifulSoup 中将一个标签替换为另一个标签 的相关文章

随机推荐