使用R语言spotifyr库调用Spotify API时遭遇429请求失败错误
解决Spotify API 429请求超限错误
错误原因
429 是HTTP标准的请求超限错误,Spotify API对免费用户的请求频率有严格限制:
- 免费版用户每小时最多请求180次
- 如果短时间内请求次数超标,API会强制要求等待很长时间(就是你看到的
Retrying in X seconds),甚至直接拒绝请求
你的代码里有两个关键问题加剧了这个错误:
- 给艺人名字手动加了单引号,导致
get_artist_audio_features搜索不到正确艺人,产生大量无效请求,更快触发限制 - 循环请求没有添加间隔延迟,短时间内连续发送请求直接撞上限额
修复步骤
1. 完成Spotify API认证(必须步骤)
spotifyr需要你先在Spotify开发者平台创建应用,获取Client ID和Client Secret,然后设置认证:
# 替换成你自己的Client ID和Client Secret Sys.setenv(SPOTIFY_CLIENT_ID = "你的Client ID") Sys.setenv(SPOTIFY_CLIENT_SECRET = "你的Client Secret") # 获取访问令牌 access_token <- get_spotify_access_token()
未认证会使用公共令牌,速率限制极低,极易触发429错误。
2. 优化代码:移除多余单引号+添加请求延迟
修改后的完整代码:
library(rvest) library(dplyr) library(spotifyr) library(tidyr) # 设置Spotify API认证(替换成你的信息) Sys.setenv(SPOTIFY_CLIENT_ID = "你的Client ID") Sys.setenv(SPOTIFY_CLIENT_SECRET = "你的Client Secret") get_spotify_access_token() # 爬取艺人数据 upcoming_artists <- read_html("https://newsroom.spotify.com/2020-03-09/36-new-artists-around-the-world-that-are-on-spotifys-radar/") %>% html_elements("tbody") %>% html_table() %>% `[[`(1) %>% separate_rows(X2, sep = "\n") # 筛选印度艺人 upcoming_artists_india <- upcoming_artists[33:35,] upcoming_artists_india_list <- list() # 循环请求,每次请求后添加延迟 for(i in 1:nrow(upcoming_artists_india)) { artist_name <- upcoming_artists_india$X2[i] # 直接传艺人名字,不要加单引号 upcoming_artists_india_list[[i]] <- get_artist_audio_features(artist_name) # 每次请求后等待3秒,避免触发速率限制 Sys.sleep(3) }
3. 额外优化建议
如果需要批量获取大量艺人数据,建议分批次请求,每请求10-15次就暂停1-2分钟;也可以用purrr包实现更优雅的延迟请求:
library(purrr) # 创建带延迟的请求函数 slow_get_artist <- slowly(get_artist_audio_features, rate = rate_delay(3)) upcoming_artists_india_list <- map(upcoming_artists_india$X2, slow_get_artist)
内容的提问来源于stack exchange,提问作者driver
相关产品推荐
相关产品推荐

