【发布时间】:2017-04-24 14:02:41
【问题描述】:
我正在修改一个 BeautifulSoup 对象,但附加标签似乎实际上并未将标签附加到任何地方。更改标签的名称确实有效,但由于某种原因 .append 没有。有谁知道我做错了什么?我能想到的唯一原因是 .append-functionality 不能就地工作,而是创建一个新副本,但在官方文档中 .append 就像就地使用一样。
testclade = """
<phy:clade branch_length_attr="0.00576111248034">
<phy:name>22316-6_AHCVY7AFXX_S13.27</phy:name>
<phy:branch_length>5.761112e-03</phy:branch_length>
</phy:clade>
"""
from bs4 import BeautifulSoup as bs
soup = bs(testclade, 'xml')
clades = soup.find_all('clade')
for c in clades:
if len(c.contents) == 5:
print 'leaf clade detected, changing contents...'
# create a tag to be added
mouseovertag = soup.new_tag('annotation')
# append the mouseovertag to the leaf-clade.
# This apparently does not work, the mouseovertag is nowhere to be seen
c.append(mouseovertag)
# replace the name of the leaf clade. This does work!
c.string = 'the changed name'
print soup.prettify()
【问题讨论】:
-
我有点想通了,当我不更改 c.string 时它确实有效
标签: python xml beautifulsoup