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

通过Spotipy登录Spotify时出现报错该如何解决?

Spotify授权问题描述

我在个人项目中使用Spotify分析自己的播放列表。
在授权访问个人账户数据时,会弹出新的Spotify标签页,本该显示登录提示,却直接展示错误页面。
Error - Spotify
如果我将该链接粘贴到无痕窗口打开,确实会显示登录提示:
Login - Spotify
但我输入用户名和密码按下回车后,立刻跳回同样的错误页面。同时Jupyter Notebook中会提示*"Enter the URL you were redirected to"*,我粘贴对应URL后程序直接崩溃,报错如下:

SpotifyOauthError: error: invalid_request, error_description: code must be supplied.
我在Jupyter Notebook中使用的代码如下:

import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials

spotify = spotipy.Spotify()

cid = "x"
secret = "y"
username = "z"
uri = "localhost:8888"

client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username, scope, cid, secret, uri)

if token:
    sp = spotipy.Spotify(auth=token)
else:
    print("Can't get token for", username)

问题解答

原因说明

  • 重定向URI配置不匹配:代码中填写的重定向URI缺少http://协议前缀,且与Spotify开发者后台对应应用的重定向URI配置不完全一致,导致授权回调时无法正常获取code参数,触发报错。
  • 授权模式混用:同时初始化了仅用于访问公开数据的客户端凭证模式、和用于访问用户私有数据的用户授权模式,两类授权逻辑冲突,影响token生成流程。
  • 浏览器缓存干扰:正常模式下的旧Spotify登录会话缓存导致授权请求直接触发校验失败,无痕模式无旧缓存可进入登录页,但因前述配置问题仍无法完成授权。

修复步骤

  1. 调整重定向URI配置:在Spotify开发者后台的对应应用设置中,添加带协议前缀的重定向地址,例如http://localhost:8888/callback,再将代码中的uri变量修改为和后台配置完全相同的值。
  2. 清理冗余代码:移除客户端凭证模式相关的初始化逻辑,修正后的代码参考如下:
import spotipy
import spotipy.util as util

cid = "替换为你的客户端ID"
secret = "替换为你的客户端密钥"
username = "替换为你的Spotify用户名"
# 必须和Spotify后台配置的重定向URI完全一致
redirect_uri = "http://localhost:8888/callback"

scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username, scope, client_id=cid, client_secret=secret, redirect_uri=redirect_uri)

if token:
    sp = spotipy.Spotify(auth=token)
    # 后续业务逻辑写在此处
else:
    print("无法获取对应账号的token", username)
  1. 授权时优先使用无痕窗口操作,登录后复制完整的回调URL粘贴到Jupyter的输入框即可完成授权。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:57:03