spotify搜索API查询

时间:2018-03-30 16:09:08

标签: python spotify spotipy

enter image description here

如何从以下代码中获取关注者数量和类型以及其他结果:

q="A"
sp.search(q,limit=1,offset=0,type="artist",market="US")
followers=result['artists']['items']
pprint(followers)

[{'external_urls': {'spotify': 
'https://open.spotify.com/artist/0ZXKT0FCsLWkSLCjoBJgBX'},
'followers': {'href': None, 'total': 121213},
'genres': ['gothic metal', 'progressive metal'],
'href': 'https://api.spotify.com/v1/artists/0ZXKT0FCsLWkSLCjoBJgBX',
'id': '0ZXKT0FCsLWkSLCjoBJgBX',
'images': [{'height': 640,
          'url': 
'https://i.scdn.co/image/350538b94d7d1829d983eaf4ee4aeca2af071f2c',
          'width': 640},
         {'height': 320,
          'url': 
'https://i.scdn.co/image/1a00c2a831a77f681516d3be11f2f0c6a9bb85b2',
          'width': 320},
         {'height': 160,
          'url': 
'https://i.scdn.co/image/8066cb28d68d3ce4924f33e6eca1b3a2a391eca6',
          'width': 160}],
'name': 'Anathema',
'popularity': 53,
'type': 'artist',
'uri': 'spotify:artist:0ZXKT0FCsLWkSLCjoBJgBX'}]

1 个答案:

答案 0 :(得分:0)

对于初学者,我建议您访问以下链接,在Python中刷新数据结构:https://docs.python.org/3/tutorial/datastructures.html
但为了更直接地回答你的问题,似乎"粉丝"此处列出的列表是字典项列表。在您的情况下,列表的长度仅为1,因此您可以按如下方式访问其中的内容:

contents = followers[0]  

(注意:如果列表的长度大于1,这将只返回列表中的第一个字典项。如果长度大于1,则需要遍历列表以查找所有元素。)
这将返回与第一个且唯一的关注元素相关联的字典项。从那里,您可以通过以下方式访问字典的特定部分:

contents['genre']

contents['followers'] 

(或对字典中其他数据字段的类似调用)
现在使用第一个,引用"类型"类型,你会得到一个列表。此列表包含此特定艺术家所属的所有不同类型。在这种情况下,Anathema(返回的乐队的名字)属于哥特金属和进步金属。因此,通过访问内容[' genre']返回的列表将仅包含这两个元素 此外,内容['粉丝']将返回另一个字典:此字典包括与Anathema乐队的粉丝有关的信息。要访问关注者计数,您可以执行以下操作:

follow_count = contents['followers']['total']

这应该为您提供您正在寻找的结果。