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

如何用Python递归函数实现基于next_cursor的接口数据拉取

循环调用分页接口直到无下一页游标

修正后的完整代码

import requests
import json

current_cursor = "x"  # 替换成你的初始游标值,比如空字符串或具体初始值

def fetch_data(cursor):
    # 发送HTTP GET请求,拼接正确的查询参数
    response = requests.get(f"https://example.com?current_cursor={cursor}")
    # 主动抛出请求失败的异常,避免后续解析出错
    response.raise_for_status()
    # 直接解析响应为JSON对象,比手动loads更高效
    data = response.json()
    
    # 执行你的数据处理逻辑(替换成实际操作)
    process_data(data["data"])
    
    # 安全获取next_cursor:不存在则返回None
    next_cursor = data.get("next_cursor")
    return next_cursor

def process_data(data):
    # 这里写对返回数据的具体操作,比如存储、分析等
    print(f"完成{len(data)}条数据的处理")

# 核心循环:持续调用直到没有下一页游标
while current_cursor is not None:
    current_cursor = fetch_data(current_cursor)

关键说明

  • 补全HTTP请求逻辑:原代码仅拼接了URL字符串,未实际发起请求,这里用requests.get()完成真实请求,同时通过raise_for_status()捕获请求失败的情况(比如网络错误、接口报错)
  • 避免KeyError异常:用data.get('next_cursor')替代直接索引取值,当接口不再返回next_cursor字段时,自动返回None,不会触发异常
  • 循环终止条件:当fetch_data返回None时,while循环自动终止,结束分页拉取
  • 代码解耦:把数据处理逻辑拆分到process_data函数中,让代码结构更清晰,便于维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:08:17