InvalidSyntax
InvalidSyntax

Reputation: 9505

How to get all items through Spotipy including next page

Using the Spotipy python library I'm trying to print out all my saved songs from Spotify.

Using the following code I'm able to print out all the results from the first page that has been returned:

results = sp.current_user_saved_tracks()
for item in results['items']:
        results = sp.next(results['items'])
        track = item['track']
        label = track['artists'][0]['name'] + ' - ' + track['name'] 
        print (label)

Using some of the other examples on how to iterate through playlists that have multiple pages, I have placed a while statement to go to the next page (if one exists)

results = sp.current_user_saved_tracks()
for item in results['items']:
    while results['next']:
        results = sp.next(results['items'])
        track = item['track']
        label = track['artists'][0]['name'] + ' - ' + track['name'] 
        print (label)

But this doesn't work, I get the following error:

TypeError: list indices must be integers or slices, not str

This is what the get user tracks structure looks like from the Spotify API

{
  "href": "https://api.spotify.com/v1/me/tracks?offset=0&limit=50",
  "items": []
  "limit": 50,
  "next": "https://api.spotify.com/v1/me/tracks?offset=50&limit=50",
  "offset": 0,
  "previous": null,
  "total": 414
}

Inside the items array there are tracks which I have committed because there are too many.

Can someone explain how to correctly go through to the next pages and continue the for loop?

Upvotes: 0

Views: 1075

Answers (2)

InvalidSyntax
InvalidSyntax

Reputation: 9505

Figured it out:

results = sp.current_user_saved_tracks()
tracks = results['items']
while results['next']:
    results = sp.next(results)
    tracks.extend(results['items'])

for track in tracks:
    print(track['track']['name'])

Upvotes: 3

pavel krigman
pavel krigman

Reputation: 1

i think you should try:

for item in results['tracks']['items']:
    while results['tracks']['next']:
        results = sp.next(results['tracks']['items'])
        track = item['track']
        label = track['artists'][0]['name'] + ' - ' + track['name'] 
        print (label)

Upvotes: 0

Related Questions