Python Spotify API -无法使用“get_playlist_items”方法获取完整的播放列表

drnojrws  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(162)

当我想从spotify播放列表中提取所有歌曲时,即使在get请求中使用了“offset”和“limit”参数,我也只能得到前100首歌曲,我没有使用spotipy这样的库,而且我使用的是Python 3.9。
有人能帮我解决我做错的地方吗?先谢了!
我使用一个函数来指定参数和get请求。

def find_songs(self):
self.params = {
    "Content-type": "application/json",
    "Authorization": "Bearer {}".format(self.spotify_token),
    "offset": 50,
    "limit": 50
    }

    query = "https://api.spotify.com/v1/playlists/{}/tracks/".format(<playlist_URI>)
    response = requests.get(query, params=self.params)
    jsonResponse = response.json()
    jsonResponseItems = jsonResponse['tracks']['items']

然后提取播放列表中的数字总数,然后扩展responseItems,因为它被限制为100首歌曲。

while len(jsonResponseItems) < jsonResponse['tracks']["total"]:

# len(jsonResponseItems)) # this returns 100
response = requests.get(query, params=self.params)
query = "https://api.spotify.com/v1/playlists/{}/tracks?".format(<playlist_URI>)

newResponse = response.json() # create a new JSON response
jsonResponseItems.extend(newResponse['tracks']['items']) # extend JSON response items

我错过了什么?医生:https://developer.spotify.com/documentation/web-api/reference/#/operations/get-playlists-tracks

brgchamk

brgchamk1#

此代码将地址获得超过100首歌曲.
如前所述,Tranvi的主要思想是while循环保持请求平铺下一个URL为None。
如果调用获取播放列表API后还有更多歌曲,这是下一个归档的格式。偏移量由数据响应自动归档。

"next": "https://api.spotify.com/v1/playlists/<playlist id>/tracks?offset=100&limit=100",
import requests
import json

class MySong:
    CLIENT_ID = '<your client ID>'
    CLIENT_SECRET = '<your client Secret>'

    def __init__(self):
        self.get_token()

    def get_token(self):
        response = requests.post(url='https://accounts.spotify.com/api/token',
                                 data={ 'grant_type': 'client_credentials' },
                                 auth=(self.CLIENT_ID, self.CLIENT_SECRET))
        self.spotify_token = response.json()['access_token']
        
    def find_songs(self, playlist_id):
        headers = {
            'Authorization': "Bearer {}".format(self.spotify_token)
        }
        songs=[]
        url = 'https://api.spotify.com/v1/playlists/{}'.format(playlist_id)
        while True:
            response = requests.get(url, headers=headers)
            results = response.json()
            newResponse = None
            
            if (results.get("items",None) is not None):
                newResponse = results['items']
            elif (results.get("tracks",None) is not None):
                newResponse = results['tracks']['items']
            
            for item in newResponse:
                if (item is not None):
                    songs.append({
                        'id' : item['track']['id'],
                        'name': item['track']['name'],
                        'url': item['track']['external_urls']['spotify'],
                        'album_name': item['track']['album']['name'],
                        'artists': item['track']['artists'][0]['name']
                    })
            if (results.get("next",None) is not None):
                url = results['next']
            elif (results.get("tracks",None) is not None):
                url = results['tracks']['next']
            else:   # no more songs
                break
        return songs

playlist_id = '<your playlist id>' # more than 700 songs playlist
my_song = MySong()
songs = my_song.find_songs(playlist_id)

print(json.dumps(songs[:3], indent=2)) # print fisrt 3 songs

print(json.dumps(songs[-3:], indent=2)) # print last 3 songs
print(len(songs)) # print total number of songs

结果-获得超过700首歌曲

它匹配Spotify用户界面。

相关问题