【发布时间】:2016-10-26 14:02:30
【问题描述】:
我正在尝试创建一个动态循环来运行多个 URL 并从每个表中抓取数据,将所有内容连接到一个数据框中。我尝试了一些想法,如下图所示,但到目前为止没有任何效果。这种东西并不真正在我的驾驶室里,但我正在努力了解它是如何工作的。如果有人可以帮助我完成这项工作,我将不胜感激。
谢谢。
library(rvest)
#create a master dataframe to store all of the results
complete<-data.frame()
yearsVector <- c("2010", "2011", "2012", "2013", "2014", "2015")
positionVector <- c("qb", "rb", "wr", "te", "ol", "dl", "lb", "cb", "s")
for (i in 1:length(yearsVector))
{
for (j in 1:length(positionVector))
{
# create a url template
URL.base<-"http://www.nfl.com/draft/"
URL.intermediate <- "/tracker?icampaign=draft-sub_nav_bar-drafteventpage-tracker#dt-tabs:dt-by-position/dt-by-position-input:"
#create the dataframe with the dynamic values
URL <- paste0(URL.base, yearsVector, URL.intermediate, positionVector)
#print(URL)
#read the page - store the page to make debugging easier
page<- read_html(URL)
#This needs work since the page is dynamicly generated.
DF <- html_nodes(page, xpath = ".//table") %>% html_table(fill=TRUE)
#About 530 names returned, may need to search and extracted requested info.
# to find the players last names
lastnames<-str_locate_all(page, "lastName")[[1]]
names<- str_sub(page, lastnames[,2]+4, lastnames[,2]+20)
names<-str_extract(names, "[A-Z][a-zA-Z]*")
length(names[-c(1:16)])
#Still need to delete the first 16 names (don't know if this is consistent across all years
#to find the players positions
positions<-str_locate_all(page, "pos")[[1]]
ppositions<- str_sub(page, positions[,2]+4, positions[,2]+10)
pos<-str_extract(ppositions, "[A-Z]*")
pos<- pos[pos !=""]
#Still need to clean delete the first 16 names (don't know if this is consistent across all years
#store the temp values into the master dataframe
complete<-rbind(complete, DF)
}
}
我编辑了我的 OP 以合并您的代码 Dave。我想我快到了,但有些地方不太对劲。我收到了这个错误。
eval(substitute(expr), envir, enclos) 中的错误:需要单个值
我知道网址是对的!
http://postimg.org/image/ccmvmnijr/
我认为问题出在这一行:
page <- read_html(URL)
或者,也许这一行:
DF <- html_nodes(page, xpath = ".//table") %>% html_table(fill = TRUE)
你能帮我在这里越过终点线吗?谢谢!
【问题讨论】:
标签: r web-scraping rvest