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

如何循环遍历API请求体中的calendarID并递增至无数据返回?

实现遍历calendarID递增请求的方案

以下是修改后的代码,实现从指定起始ID开始,逐个递增calendarID发送API请求,直到返回无数据为止,并收集所有有效数据保存到文件:

import requests
import json

url = "http://apiurl/collectionData"
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Basic abcdeMzYxQUMyN0NGNTJBNDZEQi'
}

# 初始calendarID,可根据实际需求调整起始值
current_calendar_id = 363
all_collected_data = []

while True:
    # 动态构造请求体,每次使用单个递增的calendarID
    payload = {
        "calendarID": str(current_calendar_id),
        "businessDirectoryID": "36,37"
    }
    
    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, json=payload)
        # 检查HTTP请求是否成功
        response.raise_for_status()
        # 解析返回的JSON数据
        response_data = response.json()
        
        # 判断是否返回无数据,需根据API实际返回格式调整判断逻辑
        # 示例:如果返回空列表或空字典则视为无数据
        if not response_data:
            print(f"calendarID {current_calendar_id} 无数据,终止遍历")
            break
        
        # 将有效数据加入收集列表
        all_collected_data.extend(response_data)
        print(f"已获取calendarID {current_calendar_id} 的数据")
        
        # 递增calendarID,进入下一次循环
        current_calendar_id += 1
        
    except requests.exceptions.RequestException as e:
        print(f"请求calendarID {current_calendar_id} 时发生错误: {str(e)}")
        # 遇到错误时继续尝试下一个ID,可根据需求改为终止循环
        current_calendar_id += 1
        continue

# 将所有收集到的数据写入JSON文件
with open('How_Waste.json', 'w') as json_file:
    json.dump(all_collected_data, json_file, indent=4)

print(f"遍历完成,共收集 {len(all_collected_data)} 条数据,已保存至How_Waste.json")

关键说明

  • 动态请求体:摒弃原代码中固定多ID的字符串形式,改用字典动态更新calendarID,每次请求仅使用单个递增ID。
  • 终止条件:示例中通过判断返回数据是否为空来终止循环,实际需根据API的无数据返回格式调整(例如API返回特定状态码或提示字段)。
  • 异常处理:捕获网络请求过程中的各类异常(如连接失败、HTTP错误),避免程序意外中断,同时可灵活调整错误后的处理逻辑。
  • 数据收集:用列表统一收集所有有效数据,最后一次性写入文件,提升IO效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:15:08