使用Spotify API的current_user_recently_played时after参数失效问题求助
解决Spotify API获取一周内播放记录仅返回50条的问题
Spotify的current_user_recently_played接口单次请求最多返回50条记录,哪怕你指定了after参数过滤时间范围,也不会自动返回该时间范围内的所有数据——你需要通过分页循环请求来获取全部符合条件的记录。
问题原因
你当前的代码只发起了一次请求,所以只能拿到50条。要获取一周内的所有播放记录,需要利用API返回结果中的cursors(游标)信息,循环调用接口,直到没有更多数据或者获取到的记录时间早于你设定的一周前的时间点。
修改后的代码
from datetime import datetime, timedelta today = datetime.now() last_7_days = today - timedelta(days=7) last_7_days_unix_timestamp = int(last_7_days.timestamp()) * 1000 all_tracks = [] after_cursor = last_7_days_unix_timestamp while True: results = spobj.current_user_recently_played(limit=50, after=after_cursor) if not results.get("items"): break # 遍历当前页的记录,同时检查时间是否超出范围 for item in results["items"]: played_at = datetime.fromisoformat(item["played_at"].replace("Z", "+00:00")) if played_at < last_7_days: # 已经到了一周前的记录,直接跳出所有循环 all_tracks.append(item) after_cursor = None break all_tracks.append(item) if after_cursor is None: break # 更新游标,获取下一页数据 after_cursor = results["cursors"].get("after") if not after_cursor: break # 输出所有记录 if all_tracks: for item in all_tracks: track_name = item["track"]["name"] artist_name = item["track"]["artists"][0]["name"] print(f"Song: {track_name} - Artist: {artist_name}") else: print("No recently played songs found in the last 7 days.")
关键说明
- 分页循环:通过
while True持续请求,每次用cursors里的after值作为下一次请求的after参数,直到没有更多数据。 - 时间校验:因为API返回的记录是按从新到旧排序的,所以当遇到某条记录的播放时间早于一周前时,直接停止循环,避免无效请求。
- 数据收集:用
all_tracks列表存储所有符合条件的记录,最后统一输出。
额外注意
- Spotify API对调用次数有一定限制(免费用户默认是每小时100次请求),如果你的播放记录非常多,可能需要处理速率限制,但小型项目一般不会触发。
- 确保
spobj已经正确授权,拥有user-read-recently-played权限。
内容的提问来源于stack exchange,提问作者gonghee
相关产品推荐
相关产品推荐

