【发布时间】:2020-03-29 19:18:04
【问题描述】:
我正在尝试从网站上抓取一些艺术家的歌词,以便稍后由艺术家做一些词云。生成的 url 是为了使用 purrr map 函数从它们中抓取每一个歌词。代码运行,但过了一会儿,只恢复了一位艺术家的歌词。我需要做什么来抓取所有歌词并将它们存储在一个对象中?
代码如下:
##=----------------------------------------------INSTALL PACKAGES---------------------------------------
#install.packages("tidyverse")
##=----------------------------------------------LIBRARIES----------------------------------------------
library(rvest)
library(stringr)
library(purrr)
##=----------------------------------------------FUNCTIONS----------------------------------------------
hash<-function(x)
{
x<-read_html(x)%>%
html_nodes("cnt-letra p402_premium, p")%>%
html_text()
x<-str_remove_all(x,"[:punct:]")
x<-tolower(x)
x<-iconv(x,to ="ASCII//TRANSLIT")
x<-str_remove_all(x,"'")
}
##=----------------------------------------------MAIN CODE----------------------------------------------
url<-"https://www.letras.com/mais-acessadas/reggaeton/"
##url hashing
song<-read_html(url)%>%
html_nodes("b")%>%
html_text()
##url hashing
artist<-read_html(url)%>%
html_nodes("li a span")%>%
html_text()
#Strings Cleaning
artist_clean<-str_remove_all(artist,"[:punct:]")
artist_clean<-tolower(artist_clean)
artist_clean<-iconv(artist_clean,to ="ASCII//TRANSLIT")
artist_clean<-str_remove_all(artist_clean,"'")
artist_clean<-gsub(" ","-",artist_clean)
#Strings Cleaning
song_clean<-str_remove_all(song,"[:punct:]")
song_clean<-tolower(song_clean)
song_clean<-iconv(song_clean,to ="ASCII//TRANSLIT")
song_clean<-str_remove_all(song_clean,"'")
song_clean<-gsub(" ","-",song_clean)
home<-"https://letras.com"
##url generation
generated_urls<-paste(home, "/", artist_clean,"/", song_clean, sep = "")
generated_urls<-generated_urls[1:5]
x<-purrr::map(generated_urls,hash)
【问题讨论】:
-
当我运行代码时,我会从所有请求的 url 中获取输出。这可能是来自服务器的奇怪速率限制错误吗?
标签: r web-scraping tidyverse purrr rvest