简体   繁体   中英

Replace a tag with another tag in BeautifulSoup

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'

Any advice?

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>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM