如何通过循环实现获取前1000条API匹配历史数据?
高效获取前1000条匹配记录的实现方式
针对你的需求,这里提供两种主流实现方案,兼顾简洁性和性能:
方案一:同步循环(简单易维护)
如果对性能要求不高,同步循环是最直接的方式,代码可读性强,适合快速实现:
import time my_matches = [] # 循环10次,覆盖start=1到start=10的分页 for start_page in range(1, 11): try: batch = watcher.match.matchlist_by_puuid( region=my_region, puuid=me["puuid"], count=100, start=start_page ) my_matches.extend(batch) # 可选:添加短延迟避免触发API速率限制 time.sleep(0.1) except Exception as e: print(f"获取第{start_page}页失败: {str(e)}") # 可根据需求添加重试逻辑
注意:请先确认API的start参数定义——部分API的start是偏移量而非页码(比如start=0对应前100条,start=100对应第101-200条),如果是这种情况,循环应改为range(0, 1000, 100),避免重复或遗漏数据。
方案二:并行请求(提升效率)
如果想减少总耗时,可通过多线程或异步请求并行处理分页,适合API允许并发调用的场景:
多线程版本(基于concurrent.futures)
from concurrent.futures import ThreadPoolExecutor def fetch_batch(start_page): try: return watcher.match.matchlist_by_puuid( region=my_region, puuid=me["puuid"], count=100, start=start_page ) except Exception as e: print(f"获取第{start_page}页失败: {str(e)}") return [] # 控制并发数,避免触发API限流 with ThreadPoolExecutor(max_workers=5) as executor: results = executor.map(fetch_batch, range(1, 11)) my_matches = [] for batch in results: my_matches.extend(batch)
异步版本(若API支持异步调用)
如果你的watcher提供异步方法(比如awatcher.match.matchlist_by_puuid),可以用asyncio实现更高效的异步请求:
import asyncio async def fetch_batch(start_page): try: return await awatcher.match.matchlist_by_puuid( region=my_region, puuid=me["puuid"], count=100, start=start_page ) except Exception as e: print(f"获取第{start_page}页失败: {str(e)}") return [] async def fetch_all_matches(): tasks = [fetch_batch(page) for page in range(1, 11)] batches = await asyncio.gather(*tasks) return [match for batch in batches for match in batch] my_matches = asyncio.run(fetch_all_matches())
关键注意事项
- API速率限制:无论用哪种方式,都要遵守API的请求频率限制,避免被封禁。并行请求时建议控制并发数,或添加合理延迟。
- 错误处理:务必加入异常捕获逻辑,避免单个分页请求失败导致整个任务中断,必要时可添加重试机制。
- 参数验证:提前确认
start和count参数的官方定义,确保分页逻辑正确,避免数据重复或遗漏。
内容的提问来源于stack exchange,提问作者Clive Ulyate
相关产品推荐
相关产品推荐

