使用 Spotify API 进行网页抓取

Web scraping with Spotify API

我试图为每个流派获取 50 首歌曲,并将它们与流派名称放在一个数据框中,但出现以下错误。

Error : object 'res' not found

我知道是未定义的对象导致了问题,但我不知道如何处理它。 你能解释一下吗?

**Language:R, Environment: Exploratory Public**

    genres <- RETRY('GET', url = 'https://api.spotify.com/v1/recommendations/available-genre-seeds', query = list(access_token = get_spotify_access_token(), limit=150), quiet = TRUE) %>% content()

  m <- do.call(rbind,lapply(genres$genre, function(x) if(is.null(x)) NA else c(x)))
  genres_df <- as.data.frame(m)

  colnames(genres_df) <- c("genre")

 get_genre_track <- function(genre){ 
    track_check <- RETRY('GET', url = paste0("https://api.spotify.com/v1/search?query=genre%3A",genre),  query = list(type="track",limit = 50, offset = 0, access_token = get_spotify_access_token()), quiet = TRUE) %>% content()

    track_count <- 50

    df <- map_df(1:length(res$tracks$items), function(this_row) {
        tryCatch({
        this_track <- res$tracks$items[[this_row]]
        name <- this_track$name
        genre <- genre
        list(name = name, genre = genre)
      }, error = function(e){
          NULL
      })
    })
  }
  tracks_df <- lapply(genres_df$genre, get_genre_track) %>% bind_rows()
  tracks_df
}

(需要的库安装和用户信息省略)

在您上面链接的脚本中,res 定义如下:

res <- RETRY('GET', url = paste0("https://api.spotify.com/v1/search?query=genre%3A",genre), query = list(type="track",limit = 50, offset = numoffset, access_token = get_spotify_access_token()), quiet = TRUE) %>% content()

而在您的代码中,您似乎将该变量重命名为 track_check:

track_check <- RETRY('GET', url = paste0("https://api.spotify.com/v1/search?query=genre%3A",genre),  query = list(type="track",limit = 50, offset = 0, access_token = get_spotify_access_token()), quiet = TRUE) %>% content()

所以不要将其称为 res$tracks$items,而是 track_check$tracks$items