r - 为什么purrr包的map函数没有抓取所有的url数据?
问题描述
我正在尝试从网站上抓取一些艺术家的歌词,以便稍后由艺术家做一些文字云。生成的 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)
解决方案
我不太清楚为什么它会重复同一个,但如果你在运行 map 之前将 url 作为名称传递,它会产生预期的输出:
generated_urls[1:5] %>%
set_names() %>%
map(hash)
然后,您可以通过 url 或索引访问歌词,无论如何这可能更有用。另一种可行的方法是将您的 url 设置为 tibble 中的列并使用tibble(url = generated_urls) %>% mutate(lyrics = map(generated_url))
等。
推荐阅读
- excel - 如何链接两个excel文件和链接列
- java - 使用 Jackson 反序列化 POJO 的日期字段 - 无法正确反序列化日期字段
- wagtail - ChildPage.objects.child_of(self) 和 ParentPage.get_children() 有什么区别?
- python - 通过 PIP 安装时获取 CWD
- c++ - LNK2019 在 Visual Studio 2019 中链接 google 测试
- monetdb - 为什么我不能使用预定义的功能?
- android - 可以在用户级别跟踪 android 应用程序的卸载吗?
- java - 为什么是泛型
在返回类型之前? - excel - Excel - 格式值(掩码)VBA
- java - 没有参数的 Lambda 函数 - 无法推断函数接口类型