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

如何用Python Requests遍历cURL API分页直到返回None并合并结果

高效遍历API分页并合并结果的requests实现

优化后的代码

import requests
import json

base_url = 'https://API.API.io/'
api_key = '你的API密钥'
per_page = 500
all_results = []
current_page = 1

while True:
    params = {"page": current_page, "per_page": per_page}
    # 发送请求,使用API key作为用户名,密码留空
    response = requests.get(base_url, params=params, auth=(api_key, ''))
    # 解析JSON响应
    page_data = response.json()
    
    # 判断当前页是否有数据,无数据则终止循环
    if not page_data:
        break
    
    # 将当前页数据合并到总结果
    all_results.extend(page_data)
    current_page += 1

# 安全写入所有结果到JSON文件
with open('file.json', 'w', encoding='utf-8') as f:
    json.dump(all_results, f, ensure_ascii=False)

核心优化说明

  • 自动分页循环:用while True实现无限循环,直到接口返回空数据时自动终止,无需手动定义每一页的请求。
  • 动态参数生成:每次循环根据current_page动态生成请求参数,避免重复定义多个冗余的params变量。
  • 高效数据合并:使用extend()方法批量添加每页数据,比多次列表相加的效率更高。
  • 安全文件操作:用with语句管理文件,无需手动调用close(),确保文件正常关闭,避免资源泄漏。
  • 保持认证逻辑:保留原代码的auth参数配置,适配目标API的认证要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:34:38