我正在尝试从此website中提取数据。我对从draft selections by year
中提取数据感兴趣。年份从1963年到2018年。
网址结构中有一个通用模式。例如,其https://www.eliteprospects.com/draft/nhl-entry-draft/2018
,https://www.eliteprospects.com/draft/nhl-entry-draft/2017
等。
到目前为止,我已经成功提取了一年的数据。我已经编写了一个自定义函数,在给定输入的情况下,抓取工具将收集数据并将其以美观的数据帧格式呈现。
library(rvest)
library (tidyverse)
library (stringr)
get_draft_data<- function(draft_type, draft_year){
# replace the space between words in draft type with a '-'
draft_types<- draft_type %>%
# coerce to tibble format
as.tibble() %>%
set_names("draft_type") %>%
# replace the space between words in draft type with a '-'
mutate(draft_type = str_replace_all(draft_type, " ", "-"))
# create page url
page <- stringr::str_c("https://www.eliteprospects.com/draft/", draft_types, "/", draft_year)%>%
read_html()
# Now scrape the team data from the page
# Extract the team data
draft_team<- page %>%
html_nodes(".team") %>%
html_text()%>%
str_squish() %>%
as_tibble()
# Extract the player data
draft_player<- page %>%
html_nodes("#drafted-players .player") %>%
html_text()%>%
str_squish() %>%
as_tibble()
# Extract the seasons data
draft_season<- page %>%
html_nodes(".seasons") %>%
html_text()%>%
str_squish() %>%
as_tibble()
# Join the dataframe's together.
all_data<- cbind(draft_team, draft_player,draft_season)
return(all_data)
} # end function
# Testing the function
draft_data<-get_draft_data("nhl entry draft", 2011)
glimpse(draft_data)
Observations: 212
Variables: 3
$ value <chr> "Team", "Edmonton Oilers", "Colorado Avalanche", "Florida Panth...
$ value <chr> "Player", "Ryan Nugent-Hopkins (F)", "Gabriel Landeskog (F)", "...
$ value <chr> "Seasons", "8", "8", "7", "8", "6", "8", "8", "8", "7", "7", "3...
问题:如何修改代码以使网页url中的年份自动递增,从而使抓取工具能够提取相关数据并写入数据框。?
答案 0 :(得分:1)
我只是创建一个在给定年份抓取的函数,然后绑定该年份的行。
paste()
创建包含字符串和年份变量的动态url html_table()
直接提取出来) lapply()
bind_rows()
下面是2010年至2012年这一过程的示例。
library(rvest);library(tidyverse)
scrape.draft = function(year){
url = paste("https://www.eliteprospects.com/draft/nhl-entry-draft/",year,sep="")
out = read_html(url) %>%
html_table(header = T) %>% '[['(2) %>%
filter(!grepl("ROUND",GP)) %>%
mutate(draftYear = year)
return(out)
}
temp = lapply(2010:2012,scrape.draft) %>%
bind_rows()