【问题标题】:BeautifulSoup's .append doesn't seem to change the soup-objectBeautifulSoup 的 .append 似乎没有改变汤对象
【发布时间】: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


【解决方案1】:

如果我认为您想将新的键值对添加到 clade xml 元素的想法是正确的,那么以下内容可以完成工作,尽管感觉很麻烦。

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

它也会显示在您对 soup.prettify() 的调用中。


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

【讨论】:

  • 我想创建一个新标签而不是更改现有标签的属性,所以这对我没有多大帮助
猜你喜欢
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
相关资源
最近更新 更多