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

如何修正JSON嵌套字典解析函数,抓取所有partId=1的HTML部分到列表?

问题分析与修复:抓取API返回中partId=1的HTML内容

问题说明

现有Python函数return_complete_html,传入API返回的消息列表message_list,目标是将所有消息中partId=1的HTML部分收集到complete_list。当前函数无法正确抓取目标内容,需要修正逻辑。要求不直接通过mimeType: text/html筛选,优先以partId判断。

API返回片段(简化)

[
    {"partId": "0", "mimeType": "text/plain", "filename": "", "headers": [{"name": "Content-Type", "value": "text/plain; charset=UTF-8"}]},
    {"partId": "1", "mimeType": "text/html", "filename": "", "headers": [{"name": "Content-Type", "value": "text/html; charset=UTF-8"}]}
]

当前存在问题的代码

def return_complete_html(message_list, complete_list):
    for msg_ in message_list:
        msg_id = msg_['id']
        msg = service.users().messages().get(userId='me', id=msg_id, format='full').execute()
        payload = msg['payload']['parts']

        part_list = []
        
        for part_html in payload:
            
            # mimeType = part_html.get("mimeType")
            # if mimeType == "text/html":
            #     part_list.append(part_html)
            
            part_ID = part_html.get("partId")
            part_list.append(part_html)

问题排查

  1. 无筛选逻辑:当前代码直接将所有part加入part_list,未判断partId是否为'1'
  2. 缺少结果合并:未将筛选后的part_list添加到传入的complete_list中
  3. 忽略嵌套结构:Gmail API的邮件payload可能存在多层嵌套的parts(部分邮件的HTML内容会在子part里),当前代码只遍历了顶层parts

修复后的代码

def return_complete_html(message_list, complete_list):
    def collect_target_parts(parts, target_list):
        """递归收集所有partId为'1'的部分"""
        for part in parts:
            part_id = part.get("partId")
            if part_id == '1':
                target_list.append(part)
            # 检查是否存在嵌套的子parts,递归处理
            if 'parts' in part:
                collect_target_parts(part['parts'], target_list)

    for msg_ in message_list:
        msg_id = msg_['id']
        msg = service.users().messages().get(userId='me', id=msg_id, format='full').execute()
        payload_parts = msg['payload'].get('parts', [])
        
        part_list = []
        # 调用递归函数收集目标part
        collect_target_parts(payload_parts, part_list)
        
        # 将当前邮件的目标part合并到complete_list
        complete_list.extend(part_list)

修复说明

  1. 添加partId筛选:明确判断partId == '1',符合需求中优先以partId判断的要求
  2. 递归处理嵌套结构:新增辅助函数collect_target_parts,遍历所有层级的parts,避免遗漏嵌套在子part中的目标内容
  3. 合并结果到complete_list:使用extend将当前邮件筛选出的part_list合并到传入的complete_list中,完成函数目标
  4. 容错处理:用get('parts', [])避免payload中无parts时抛出KeyError

内容的提问来源于stack exchange,提问作者init200

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:30:25