如何在Python中使用spotipy库获取Spotify用户的关注歌手
发布时间:2023-12-28 06:13:53
要在Python中使用spotipy库获取Spotify用户的关注歌手,需要进行以下步骤:
1. 安装spotipy库:在命令行中运行以下命令来安装spotipy库:
pip install spotipy
2. 创建Spotify应用程序:首先,在Spotify开发者网站(https://developer.spotify.com/dashboard/)上创建一个新应用程序,并获取应用程序的客户端ID和客户端秘钥。请务必将重定向URI设置为http://localhost:8888/callback。
3. 设置环境变量:将客户端ID和客户端秘钥设置为环境变量。可以在代码中使用以下代码获取这些值:
import os
client_id = os.getenv('SPOTIPY_CLIENT_ID')
client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
4. 进行用户身份验证:使用以下代码进行用户身份验证,并获取访问令牌和刷新令牌:
import spotipy from spotipy.oauth2 import SpotifyOAuth scope = "user-library-read" username = "<Your Spotify username>" sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri="http://localhost:8888/callback", scope=scope, username=username))
5. 获取用户关注的艺术家:使用以下代码获取当前用户关注的所有艺术家:
artists = sp.current_user_followed_artists(limit=50)['artists']['items']
for artist in artists:
print(artist['name'])
以下是完整的示例代码:
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
client_id = os.getenv('SPOTIPY_CLIENT_ID')
client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
scope = "user-library-read"
username = "<Your Spotify username>"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri="http://localhost:8888/callback", scope=scope, username=username))
artists = sp.current_user_followed_artists(limit=50)['artists']['items']
for artist in artists:
print(artist['name'])
请将<Your Spotify username>替换为您的Spotify用户名。在运行代码之前,请确保已将客户端ID和客户端秘钥设置为环境变量。
以上就是使用spotipy库获取Spotify用户的关注歌手的方法及示例代码。希望能帮助到您!
