2016-08-22 22 views
1

我正在嘗試使用Spotipy library for python來拉取某個播放列表中的所有曲目。Spotipy:如何從播放列表中讀取超過100首曲目

無論參數限制如何,user_playlist_tracks函數都限制爲100個軌道。該Spotipy文檔描述爲:

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.

與Spotify的認證後,我目前使用的是這樣的:

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

有沒有辦法返回超過100首曲目?我試着在函數參數中設置limit = None,但是它返回一個錯誤。

回答

5

許多spotipy方法返回分頁結果,所以你必須通過他們滾動查看不僅僅是最大極限。我遇到這個最經常收集時播放列表的全程跟蹤上市,並因此創造了一個自定義的方法來處理這個問題:

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 
0

以下是在spotipy中使用的user_playlist_tracks模塊。 (注意它默認爲100限制)。

嘗試將限制設置爲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) 
+0

任何超過100導致此錯誤:'spotipy.client.SpotifyException:HTTP狀態:400,代碼:-1 - https://api.spotify.com/v1/users/im.nick.hello/playlists/7lArr0TzHvKoEsj6cotHqZ/tracks?limit=200&offset=0: 無效的限制# – npbecker

+0

@NickBecker查看此鏈接spotify web API。 https://developer.spotify.com/web-api/get-playlist/ 您需要在分頁對象中使用'offset'鍵。在上面的文章中,您可以看到代碼允許使用'offset'參數。您必須多次調用API,調整每次調用的偏移量。 – rvisio

相關問題