使用 RVEST 从体育参考资料中抓取表格
Scraping tables from sports reference with RVEST
我正在尝试从此网页中抓取各种 table:https://www.pro-football-reference.com/years/2020/
在检查页面元素时,我发现使用以下代码很容易获得前两个table:
### packages
library(tidyverse)
library(rvest)
### Scrape offense
url_off <- read_html("https://www.pro-football-reference.com/years/2020/")
## AFC Standings
url_off %>%
html_table(fill = TRUE) %>%
.[1] %>%
as.data.frame()
## NFC Standings
url_off %>%
html_table(fill = TRUE) %>%
.[2] %>%
as.data.frame()
我被卡住的地方是该页面上的所有其他 table。
例如冒犯table,我可以看到它在页面上的位置:
我尝试了几种提取方法,但都没有成功。例如:
url_off %>%
html_nodes(".table_outer_container") %>%
html_nodes("#team_stats")
url_off %>%
html_nodes(".table_wrapper") %>%
html_nodes("#team_stats")
当我尝试从该页面提取任何其他 table 时,这似乎是一个问题。我能得到的唯一两个 table 是前两个(上面)。我不知道我哪里出错了。
我已经解决了。数据都存储为评论,我认为这是我的问题。对于任何感兴趣或有类似问题的人,这是我提取表格的方式:
url_off %>%
html_nodes('#all_team_stats') %>%
html_nodes(xpath = 'comment()') %>%
html_text() %>%
read_html() %>%
html_node('table') %>%
html_table()
url_off %>%
html_nodes('#all_passing') %>%
html_nodes(xpath = 'comment()') %>%
html_text() %>%
read_html() %>%
html_node('table') %>%
html_table()
我正在尝试从此网页中抓取各种 table:https://www.pro-football-reference.com/years/2020/
在检查页面元素时,我发现使用以下代码很容易获得前两个table:
### packages
library(tidyverse)
library(rvest)
### Scrape offense
url_off <- read_html("https://www.pro-football-reference.com/years/2020/")
## AFC Standings
url_off %>%
html_table(fill = TRUE) %>%
.[1] %>%
as.data.frame()
## NFC Standings
url_off %>%
html_table(fill = TRUE) %>%
.[2] %>%
as.data.frame()
我被卡住的地方是该页面上的所有其他 table。
例如冒犯table,我可以看到它在页面上的位置:
我尝试了几种提取方法,但都没有成功。例如:
url_off %>%
html_nodes(".table_outer_container") %>%
html_nodes("#team_stats")
url_off %>%
html_nodes(".table_wrapper") %>%
html_nodes("#team_stats")
当我尝试从该页面提取任何其他 table 时,这似乎是一个问题。我能得到的唯一两个 table 是前两个(上面)。我不知道我哪里出错了。
我已经解决了。数据都存储为评论,我认为这是我的问题。对于任何感兴趣或有类似问题的人,这是我提取表格的方式:
url_off %>%
html_nodes('#all_team_stats') %>%
html_nodes(xpath = 'comment()') %>%
html_text() %>%
read_html() %>%
html_node('table') %>%
html_table()
url_off %>%
html_nodes('#all_passing') %>%
html_nodes(xpath = 'comment()') %>%
html_text() %>%
read_html() %>%
html_node('table') %>%
html_table()