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

requests.get()未跟随Spotify OAuth授权URL重定向问题排查

解决Spotify OAuth授权URL用requests.get无法获取带code的重定向地址问题

问题原因

  • Spotify的OAuth授权流程必须经过用户交互环节:浏览器打开授权URL后,会引导你完成登录、确认权限操作,这两步完成后才会跳转到带code的redirect_uri。但requests.get是无状态的HTTP请求工具,它没有浏览器的会话管理能力,也没法模拟用户登录和授权操作。
  • 你看到的<Response [303]>是授权URL返回的重定向,目标其实是Spotify的登录页面,而非你的redirect_uri。因为requests无法完成登录授权,后续请求会卡在登录流程里,所以最终的r.url不会出现带code的地址,r.history里的URL也还是原授权URL。

解决办法

方法一:用浏览器自动化工具模拟完整流程

用Selenium这类工具模拟浏览器的登录、授权操作,完整走通OAuth流程来获取code,示例代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 替换成你的授权URL
authorization_url = "https://accounts.spotify.com/authorize?client_id=xxx&response_type=code&redirect_uri=xxx&scope=xxx"
driver = webdriver.Chrome()
driver.get(authorization_url)

# 填写Spotify账号信息(根据实际页面元素调整定位方式)
driver.find_element(By.ID, "login-username").send_keys("你的Spotify用户名")
driver.find_element(By.ID, "login-password").send_keys("你的Spotify密码")
driver.find_element(By.ID, "login-button").click()

# 等待授权页面加载,点击授权按钮(如果账号已登录过,可能跳过这步)
time.sleep(2)
try:
    driver.find_element(By.ID, "auth-accept").click()
except:
    pass

# 提取URL中的code参数
final_url = driver.current_url
code = final_url.split("code=")[1].split("&")[0]
print(f"获取到的授权code:{code}")

driver.quit()

方法二:手动获取code复用(适合测试场景)

如果只是测试接口,直接用浏览器打开授权URL,手动完成登录授权后,复制地址栏中带code的URL,把code提取出来直接在代码中使用即可,无需自动获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:27:02