2017-05-04 127 views
1

我無法通過Spotipy從Spotify上的軌道打印信息。Spotipy:打印跟蹤信息

我現在有以下代碼:

import spotipy 
import sys 
import json 

urn = 'spotify:track:450vazRH94IB21mom5FkN9' 
sp = spotipy.Spotify() 
track_info = sp.track(urn) 
artist_name = track_info['album']['artists'] 
artist_name 

它輸出:

[{ 'external_urls':{ 'Spotify的': 'https://open.spotify.com/artist/0YWxKQj2Go9CGHCp77UOyy '}, 'HREF':' https://api.spotify.com/v1/artists/0YWxKQj2Go9CGHCp77UOyy', '身份證': '0YWxKQj2Go9CGHCp77UOyy', '名': '非常棒', '類型': '藝術家', 'URI': 'Spotify的:藝術家:0YWxKQj2Go9CGHCp77UOyy'}]

當我嘗試使用這位演出= track_info [ '專輯'] [ '藝術家'],並添加['名稱]到最後,就像這樣:

artist_name = track_info['album']['artists']['name'] 

我得到這個錯誤:

類型錯誤:列表索引必須是整數或切片,而不是str

我不太確定它爲什麼說這是一個字符串。

回答

1

track_info['album']['artists']是一個列表,你需要使用指數(list[0]),以獲得項目:

artist_name = track_info['album']['artists'][0]['name'] 

它可以是多個藝術家。在這種情況下使用list comprehension

artist_names = [artist['name'] for artist in track_info['album']['artists']]