gpt4 book ai didi

python - 在 BeautifulSoup 中用另一个标签替换一个标签

转载 作者:行者123 更新时间:2023-12-04 00:41:43 26 4
gpt4 key购买 nike

我正在尝试在 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'

有什么建议吗?

最佳答案

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

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>

希望这会有所帮助。

关于python - 在 BeautifulSoup 中用另一个标签替换一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com