我正在尝试通过 python 中的 Spotify-API 从播放列表中获取每个曲目名称和艺术家姓名。 (https://developer.spotify.com/documentation/web-api/reference/get-playlist)
问题是响应将显示的项目数有限制(100)。解决方案是从播放列表中获取“下一个”属性,该属性基本上是从中获取接下来的 100 个项目(通过偏移量)。 但是当我尝试从我的响应中获取
['track']
属性时,就像在第一次调用中一样,python 告诉我它的“无”。
有人有该 API 的经验并且知道如何修复该错误吗?也许我正在监督一些显而易见的事情......
代码:
def get_playlist_track_list(playlist_id):
url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
headers = get_auth_header(token)
total_tracks = 0
tracklist = []
while True:
result = get(url, headers=headers)
response = result.json()
total_tracks = response['total']
items = response['items']
for item in items:
track_name = item['track']['name']
artist_name = item['track']['artists'][0]['name']
# Check if track_name and artist_name are not None
if track_name is not None and artist_name is not None:
track_name = clean(str(track_name))
artist_name = clean(str(artist_name))
tracklist.append(f"{artist_name} - {track_name}")
# Check if there are more tracks to fetch
if response['next']:
url = response['next'] # Set the URL to the next batch of tracks
else:
break # Exit the loop if there are no more tracks
return "\n".join(tracklist)
我查看了json结构,它是一样的。