在 R 中使用 rvest 包抓取 soundcloud.com

Scraping soundcloud.com with rvest package in R

我正在尝试抓取这个 URL 以获取加拿大前 50 名 soundcloud 艺术家的名字。

使用 SelectorGadget,我选择了艺术家的名字,它告诉我路径是“.sc-link-light”。

我的第一次尝试如下:

library(rvest)
library(stringr)
library(reshape2)

soundcloud <- read_html("https://soundcloud.com/charts/top?genre=all-music&country=CA")

artist_name <- soundcloud %>% html_nodes('.sc-link-light') %>% html_text()

产生 artist_name 作为 0 的列表。

我第二次尝试将最后一行更改为:

artist_name <- soundcloud %>% html_node(xpath='//*[contains(concat( " ", @class, " " ), concat( " ", ".sc-link-light", " " ))]') %>% html_text()

再次产生相同的结果。

我到底做错了什么?我相信这应该给我列表中的艺术家姓名。 感谢任何帮助,谢谢。

您尝试抓取的网页是动态的。因此,您将需要使用诸如 RSelenium 之类的库。示例脚本如下:

library(tidyverse)
library(RSelenium)
library(rvest)
library(stringr)

url <- "https://soundcloud.com/charts/top?genre=all-music&country=CA"

rD <- rsDriver(browser = "chrome")
remDr <- rD[["client"]]


remDr$navigate(url)
pg <- read_html(remDr$getPageSource()[[1]])
artist_name <- pg %>% html_nodes('.sc-link-light') %>% html_text()


####clean up####
remDr$close()
rD$server$stop()
rm(rD, remDr)
gc()

system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)