Python调用Twitch API获取关注频道列表循环异常求助
解决Twitch API获取关注列表时的无限循环与数据填充问题
嘿,我来帮你捋捋这个问题!你正在做的Twitch头部频道关注网络项目听起来挺有意思的,但作为Python新手碰到这种无限循环和数据填充异常的问题确实闹心,咱们一步步来解决它。
问题根源分析
先说说为啥会出现无限循环和append异常:
- 无限循环:你的
while循环条件是len(seguiti) < follows_json['_total'],但如果某次API请求返回的关注列表是空的(比如已经到最后一页,或者API返回了错误),seguiti的长度就不会增长,循环就会一直跑下去。而且你每次只累加off +=100,但没考虑到_total可能不是100的整数倍,最后一页的结果会少于100条,这时候继续累加off就会请求到空数据。 - append异常:
k['channel']['display_name']报错,大概率是因为API返回的JSON里没有follows字段,或者某个k里没有channel键——比如请求被限流了、用户不存在,或者API返回了错误信息,这时候解析JSON就会触发KeyError。
修复后的代码方案
我给你调整了代码,加了错误处理、完善了分页逻辑,还加了注释方便你理解:
import requests import json def get_twitch_follows(username, client_id): seguiti = [] offset = 0 limit = 100 base_url = 'https://api.twitch.tv/kraken/users/{}/follows/channels' # 第一次请求获取总数量 try: response = requests.get(base_url.format(username), params={ 'client_id': client_id, 'offset': offset, 'limit': limit }) response.raise_for_status() # 检查请求是否成功(比如404、429限流) follows_json = response.json() total_follows = follows_json.get('_total', 0) if total_follows == 0: print(f"{username}没有关注任何频道") return seguiti # 处理第一页数据 for follow in follows_json.get('follows', []): try: channel_name = follow['channel']['display_name'] seguiti.append(channel_name) except KeyError: print(f"解析关注数据时出错:缺少channel或display_name字段") continue # 分页获取剩余数据 while len(seguiti) < total_follows: offset += limit # 提前判断offset是否超过总数量,避免无效请求 if offset >= total_follows: break try: response = requests.get(base_url.format(username), params={ 'client_id': client_id, 'offset': offset, 'limit': limit }) response.raise_for_status() follows_json = response.json() current_follows = follows_json.get('follows', []) # 如果当前页没有数据,直接跳出循环(防止无限循环) if not current_follows: print(f"分页请求未返回数据,提前结束循环") break for follow in current_follows: try: channel_name = follow['channel']['display_name'] seguiti.append(channel_name) except KeyError: print(f"解析分页数据时出错:缺少channel或display_name字段") continue except requests.exceptions.RequestException as e: print(f"请求API时出错:{e}") break # 请求出错就停止循环,避免无限重试 print(f"成功获取{username}的{len(seguiti)}条关注数据(总共有{total_follows}条)") return seguiti except requests.exceptions.RequestException as e: print(f"初始请求出错:{e}") return seguiti # 测试代码 client_id = "你的Client ID" # 记得替换成你的实际Client ID top_channel = ['Ninja'] all_follows = [] for user in top_channel: print(f"正在处理用户:{user}") user_follows = get_twitch_follows(user, client_id) all_follows.extend(user_follows) print(f"总共获取到{len(all_follows)}条关注数据") print(all_follows)
关键改动说明
- 封装函数:把获取单个用户关注列表的逻辑封装成函数,更清晰,也方便复用和调试。
- 错误处理:
- 用
response.raise_for_status()捕获请求错误(比如429限流、404用户不存在) - 用
try-except捕获KeyError,避免因为JSON字段缺失导致程序崩溃
- 用
- 完善分页逻辑:
- 提前判断
offset是否超过total_follows,避免无效请求 - 检查当前页返回的
follows是否为空,如果为空就跳出循环,防止无限循环
- 提前判断
- 参数传递优化:用
params字典传递API参数,比直接拼接URL更安全,也更容易维护
额外提醒
- Twitch的Kraken API是旧版API,现在官方推荐使用Helix API,如果后续项目扩展,建议切换到新版API,功能更全也更稳定。
- 注意API的请求频率限制,Kraken API的限流是每10分钟1000次请求,如果请求频繁可能会被限流,这时候可以加个延时(比如
time.sleep(1))或者处理429状态码的重试逻辑。
内容的提问来源于stack exchange,提问作者Isabella Shiro Sina
相关产品推荐
相关产品推荐

