BeautifulSoup的.append似乎没有改变汤对象

时间:2017-04-24 14:02:42

标签: python xml beautifulsoup

我正在修改一个BeautifulSoup对象,但是附加一个标记似乎并没有将标记实际附加到任何地方。更改标记的名称确实有效,但由于某种原因,.append不会。有谁知道我做错了什么?我能想到的唯一原因是.append功能不能就地工作,而是创建一个新的副本,但在官方文档中.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()

1 个答案:

答案 0 :(得分:0)

如果我认为你想要为clade xml元素添加一个新的键值对是正确的,那么下面的工作就完成了,虽然感觉很糟糕。

c.attrs['annotation'] = 'the changed name'

它也显示在您对soup.prettify()的通话中。

查看documentation .new_tag()是为了将 new xml标记附加到所选元素,而不是修改现有元素。