BeautifulSoup的。append似乎不会改变soupbj

2024-06-28 18:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在修改一个beauthoulGroup对象,但是附加一个标记似乎并没有实际地将标记附加到任何地方。更改标记的名称确实有效,但由于某些原因,.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()

Tags: thetoname标记branchbsphy原因
1条回答
网友
1楼 · 发布于 2024-06-28 18:56:30

如果我认为您想向cladexml元素添加一个新的键值对,那么下面的代码就完成了这项工作,尽管感觉很糟糕。在

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

它也会出现在你对soup.prettify()的调用中。在


查看documentation.new_tag()是为了给所选元素添加一个新的xml标记,而不是修改现有的元素。在

相关问题 更多 >