You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析XML时字典多次存储相同结果是什么原因?

问题根因

  • 你将向列表追加动漫信息的anime_details.append()逻辑写在了遍历<info>标签的循环内部,每处理1个<info>标签就会插入1条记录,单个动漫节点下有多少个<info>子标签,最终就会生成多少条重复的动漫记录。
  • title、pic、plot三个变量为全局初始化,若后续需要解析多个动漫节点,前一个动漫的字段值会残留到下一个动漫的记录中,会导致数据错误。

修复后代码

anime_list = []

# 先遍历所有anime节点,适配多动漫返回的场景
for anime_node in anime_info.findall('anime'):
    # 每个动漫单独初始化字段,避免数据残留
    title = None
    pic = None
    plot = None
    # 遍历当前动漫下的所有info标签
    for tag in anime_node.findall('info'):
        tag_type = tag.attrib['type']
        if tag_type == 'Picture':
            pic = tag.attrib['src']
        elif tag_type == 'Main title':
            title = tag.text
        elif tag_type == "Plot Summary":
            plot = tag.text
    # 所有info标签处理完成后,仅追加一次当前动漫的完整信息
    anime_list.append({'title': title, 'picture': pic, 'plot': plot})

# 打印结果
for anime in anime_list:
    print(anime['title'])
    print(anime['picture'])
    print(anime['plot'])

内容的提问来源于stack exchange,提问作者Drey's

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:54:03