You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Spotify Search API查询代码中获取粉丝数、流派及其他结果

嘿,我来帮你拆解怎么从Spotify Search API的返回结果里提取你要的数据~

从Spotify Search API结果中提取粉丝数、流派及其他数据

首先得明确:你的API返回里,result['artists']['items']是一个包含艺术家对象的列表(哪怕你设置了limit=1,它依然是列表格式),所以第一步要先取出列表里的单个艺术家条目,之后再提取对应字段就简单多了。

1. 提取粉丝数

粉丝总数藏在followers字段的total属性里,直接取值即可:

# 先获取第一个艺术家对象
artist = result['artists']['items'][0]
# 提取粉丝数
followers_count = artist['followers']['total']
# 示例里会得到 121213

注意:followers里的href字段通常是None,这是Spotify API的正常返回,它不会提供粉丝列表的直接链接,只会返回总数。

2. 提取流派

流派是一个字符串列表,直接取genres字段就行:

genres = artist['genres']
# 示例里会得到 ['gothic metal', 'progressive metal']

如果某个艺术家没有被标注流派,这个列表会是空的,处理时可以加个判断避免空值问题。

3. 提取其他常用数据

给你整理几个常见字段的提取方式:

  • 艺术家Spotify唯一ID:
artist_id = artist['id']
  • 艺术家的Spotify官方链接:
spotify_url = artist['external_urls']['spotify']
  • 艺术家头像图片(优先取最高分辨率的,即列表第一个元素):
# 做容错处理,避免没有头像的情况
artist_image_url = artist['images'][0]['url'] if artist['images'] else None
  • 艺术家的API详情接口链接:
artist_api_href = artist['href']

完整可运行示例代码

把这些逻辑整合起来,你的代码可以写成这样:

import pprint
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# 初始化Spotify客户端(记得替换成你自己的client_id和client_secret)
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET'
))

q = "A"
result = sp.search(q, limit=1, offset=0, type="artist", market="US")

# 先判断是否搜索到结果,避免索引错误
if result['artists']['items']:
    artist = result['artists']['items'][0]
    
    # 逐一提取数据
    followers_count = artist['followers']['total']
    genres = artist['genres']
    artist_id = artist['id']
    spotify_url = artist['external_urls']['spotify']
    artist_image_url = artist['images'][0]['url'] if artist['images'] else None
    
    # 打印输出结果
    print(f"粉丝数: {followers_count}")
    print(f"流派: {', '.join(genres) if genres else '无标注流派'}")
    print(f"艺术家ID: {artist_id}")
    print(f"Spotify链接: {spotify_url}")
    print(f"头像链接: {artist_image_url if artist_image_url else '无头像'}")
else:
    print("没有找到匹配的艺术家")

注意事项

  • 一定要先判断result['artists']['items']是否为空,否则搜索不到结果时会触发索引错误。
  • 像images这类字段可能为空,必须做容错处理,避免抛出KeyError或IndexError。

内容的提问来源于stack exchange,提问作者Madhav Vadalia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:16:05