簡體   English   中英

用BeautifulSoup中的另一個標簽替換標簽

[英]Replace a tag with another tag in BeautifulSoup

我正在嘗試在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>

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM