Spotipy: How to read more than 100 tracks from a p

2020-06-17 05:54发布

问题:

I'm trying to pull all tracks in a certain playlist using the Spotipy library for python.

The user_playlist_tracks function is limited to 100 tracks, regardless of the parameter limit. The Spotipy documentation describes it as:

user_playlist_tracks(user, playlist_id=None, fields=None, limit=100, offset=0, market=None)

Get full details of the tracks of a playlist owned by a user.

Parameters:

  • user
  • the id of the user playlist_id
  • the id of the playlist fields
  • which fields to return limit
  • the maximum number of tracks to return offset
  • the index of the first track to return market
  • an ISO 3166-1 alpha-2 country code.

After authenticating with Spotify, I'm currently using something like this:

username = xxxx
playlist = #fromspotipy
sp_playlist = sp.user_playlist_tracks(username, playlist_id=playlist)
tracks = sp_playlist['items']
print tracks

Is there a way to return more than 100 tracks? I've tried setting the limit=None in the function parameters, but it returns an error.

回答1:

Many of the spotipy methods return paginated results, so you will have to scroll through them to view more than just the max limit. I've encountered this most often when collecting a playlist's full track listing and consequently created a custom method to handle this:

def get_playlist_tracks(username,playlist_id):
    results = sp.user_playlist_tracks(username,playlist_id)
    tracks = results['items']
    while results['next']:
        results = sp.next(results)
        tracks.extend(results['items'])
    return tracks


回答2:

Another way around it would be to write a for loop and do:

offset +=100

then you could concatenate the tracks at the end, or put them in a data frame. Function Ref:

playlist_tracks(playlist_id, fields=None, limit=100, offset=0, market=None)

Reference: https://spotipy.readthedocs.io/en/2.7.0/#spotipy.client.Spotify.playlist_tracks



回答3:

Below is the user_playlist_tracks module used in spotipy. (notice it defaults to 100 limit).

Try setting the limit to 200.

def user_playlist_tracks(self, user, playlist_id = None,   fields=None,
    limit=100, offset=0):
    ''' Get full details of the tracks of a playlist owned by a user.

        Parameters:
            - user - the id of the user
            - playlist_id - the id of the playlist
            - fields - which fields to return
            - limit - the maximum number of tracks to return
            - offset - the index of the first track to return
    '''
    plid = self._get_id('playlist', playlist_id)
    return self._get("users/%s/playlists/%s/tracks" % (user, plid),
                limit=limit, offset=offset, fields=fields)