2017-05-04 168 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']]