如何通过用户ID使用Spotipy获取Spotify用户的名称?
使用Spotipy获取Spotify用户显示名称的可行方案
- 核心方法是调用Spotipy的
spotify.user()接口,该接口会返回目标用户的公开信息,其中就包含当前显示名称(对应字段display_name)。 - 如果要获取当前授权用户的显示名称,可直接用
spotify.current_user()接口,无需传入用户ID。
代码示例(获取指定用户ID的显示名称)
import spotipy from spotipy.oauth2 import SpotifyClientCredentials # 初始化Spotipy客户端 client_creds = SpotifyClientCredentials(client_id='你的Client ID', client_secret='你的Client Secret') sp = spotipy.Spotify(client_credentials_manager=client_creds) # 替换为目标用户的Spotify ID target_user_id = "要查询的用户ID" user_profile = sp.user(target_user_id) # 提取显示名称,无名称时返回默认值 user_display_name = user_profile.get('display_name', '未设置显示名称') print(f"用户显示名称:{user_display_name}")
补充说明
- 若用户设置了私密信息权限,仅能获取其公开可见的信息;获取当前授权用户的完整信息需确保授权时包含
user-read-private或user-read-public权限。 spotify.current_user()的用法更简单,直接返回当前登录用户的所有信息,同样通过display_name字段提取名称。
内容的提问来源于stack exchange,提问作者thatjamesemo
相关产品推荐
相关产品推荐

