用Rvest和胶包在R中刮擦
我正在尝试使用rvest和glue包来抓取多页的体育数据。我在嵌套方面遇到了问题,我认为这是因为网站的表有两行标题(有些标题是一行,有些是两行)。以下是我开始使用的代码。我检查了一下,以确保该站点允许使用python进行抓取,并且在那里一切正常用Rvest和胶包在R中刮擦,r,web-scraping,rvest,r-glue,R,Web Scraping,Rvest,R Glue,我正在尝试使用rvest和glue包来抓取多页的体育数据。我在嵌套方面遇到了问题,我认为这是因为网站的表有两行标题(有些标题是一行,有些是两行)。以下是我开始使用的代码。我检查了一下,以确保该站点允许使用python进行抓取,并且在那里一切正常 library(tidyverse) library(rvest) # interacting with html and webcontent library(glue) 网页: 用于在1:17和1:4位置刮取选定周的功能: salary_scra
library(tidyverse)
library(rvest) # interacting with html and webcontent
library(glue)
网页:
用于在1:17和1:4位置刮取选定周的功能:
salary_scrape_19 <- function(week, position) {
Sys.sleep(3)
cat(".")
url <- glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
read_html(url) %>%
html_nodes("table") %>%
html_table() %>%
purrr::flatten_df() %>%
#set_names(need to clean headers before I can set this)
}
scraped_df <- scaffold %>%
mutate(data = map2(week, position, ~salary_scrape_19(.x, .y)))
scraped_df
salary\u scrape\u 19%
html_表()%>%
purrr::展平_df()%>%
#设置_名称(需要先清除标题才能设置此名称)
}
刮除的_df%
变异(数据=map2(周,职位,~salary\u scrape\u 19(.x,.y)))
刮伤
最终,我想构建一个scrape函数,以获得2019年所有周内具有相同列(QB、RB、WR和TE)的所有职位。(希望最终添加第三个变量来粘合{year},但需要先获得该变量
同样,我认为这个问题与网站上表格的不稳定标题有关,因为有些标题是一行,而其他标题是两行。我们可以将第一行作为列名粘贴到原始列,然后删除该行
library(tidyverse)
library(rvest)
salary_scrape_19 <- function(week, position) {
url <- glue::glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
read_html(url) %>%
html_nodes("table") %>%
html_table() %>%
.[[1]] %>%
set_names(paste0(names(.), .[1, ])) %>%
slice(-1)
}
这完全破坏了数据。我现在甚至看不到“码”列。@Jefferson我更新了答案,将两个标题组合在一起。你现在能检查一下吗?
scaffold <- data.frame(week = c(1, 2), position = c(1, 2))
scraped_df <- scaffold %>% mutate(data = map2(week, position, salary_scrape_19))