【发布时间】:2020-11-06 23:29:04
【问题描述】:
这是我的问题:我生成的这个列表包含大量链接,我想获取这个列表并对其应用一个函数来从所有这些链接中抓取一些数据;但是,当我运行程序时,它只从该元素的第一个链接获取数据,重新打印该信息以获得正确的迭代次数。到目前为止,这是我的所有代码:
library(tidyverse)
library(rvest)
source_link<-"http://www.ufcstats.com/statistics/fighters?char=a&page=all"
source_link_html<-read_html(source_link)
#This scrapes all the links for the pages of all the fighters
links_vector<-source_link_html%>%
html_nodes("div ul li a")%>%
html_attr("href")%>%
#This seq selects the 26 needed links, i.e. from a-z
.[1:26]
#Modifies the pulled data so the links become useable and contain all the fighers instead of just some
links_vector_modded<-str_c("http://www.ufcstats.com", links_vector,"&page=all")
fighter_links<-sapply(links_vector_modded, function(links_vector_modded){
read_html(links_vector_modded[])%>%
html_nodes("tr td a")%>%
html_attr("href")%>%
.[seq(1,length(.),3)]%>%
na.omit(fighter_links)
})
###Next Portion: Using the above links to further harvest
#Take all the links within an element of fighter_links and run it through the function career_data to scrape all the statistics from said pages.
fighter_profiles_a<-map(fighter_links$`http://www.ufcstats.com/statistics/fighters?char=a&page=all`, function(career_data){
#Below is where I believe my problem lies
read_html()%>%
html_nodes("div ul li")%>%
html_text()
})
我遇到的问题在代码的最后一部分,read_html()。我不知道如何将列表中元素中的每个链接应用于该函数。另外,有没有办法调用fighter_links 的所有元素,而不是一次调用一个元素?
感谢您的任何建议和帮助!
【问题讨论】:
-
如果您不需要最新数据,您可以通过从 kaggle(战斗和战士)获取数据来避免报废:kaggle.com/rajeevw/ufcdata
-
谢谢你,DPH,太棒了!我肯定会玩弄这些数据。但是,我这样做是为了数据和学习 R,所以我想知道如何解决这个问题
标签: r web-scraping purrr