Spotify API:如何将推荐内容限制为特定艺术家作品?
解决Spotify推荐接口仅返回特定艺术家曲目的问题
Spotify官方的推荐API(对应Spotipy的recommendations方法)确实没有提供直接限制结果仅包含特定艺术家的参数——那些可调的音频特征参数只负责过滤曲目音质属性,没法约束艺术家维度。
要实现你的需求,可行的方案分两步:
- 先用目标艺术家ID作为
seed_artists参数调用推荐接口,让系统基于该艺术家的风格生成候选推荐池 - 在本地对返回的曲目列表做二次过滤,只保留归属目标艺术家的条目
具体代码实现
首先初始化Spotipy客户端并获取目标艺术家的ID:
import spotipy from spotipy.oauth2 import SpotifyOAuth # 初始化客户端(替换为你的应用信息) sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id="你的客户端ID", client_secret="你的客户端密钥", redirect_uri="你的重定向URI", scope="user-top-read" )) # 搜索目标艺术家并获取ID target_artist_name = "Radiohead" search_result = sp.search(q=f"artist:{target_artist_name}", type="artist") target_artist_id = search_result['artists']['items'][0]['id']
然后调用推荐接口并过滤结果:
# 基于目标艺术家生成推荐候选 recommendations = sp.recommendations(seed_artists=[target_artist_id], limit=50) # 过滤出仅包含目标艺术家的曲目 filtered_tracks = [] for track in recommendations['tracks']: for artist in track['artists']: if artist['id'] == target_artist_id: filtered_tracks.append(track) break # 打印过滤后的结果 for track in filtered_tracks: track_artists = ", ".join([a['name'] for a in track['artists']]) print(f"{track['name']} - {track_artists}")
额外建议
如果你的需求其实是获取该艺术家自身的优质曲目(而非跨艺人的风格推荐),直接调用artist_top_tracks接口会更高效:
# 获取目标艺术家的热门曲目 top_tracks = sp.artist_top_tracks(target_artist_id, country='CN') for track in top_tracks['tracks']: print(f"{track['name']}")
内容的提问来源于stack exchange,提问作者abdch
相关产品推荐
相关产品推荐

