用RVEST从体育参考中刮表

uinbv5nw  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(81)

我试图从这个网页上抓取各种表格:https://www.pro-football-reference.com/years/2020/
在检查页面的元素时,我发现通过使用以下代码很容易获得前两个表:

### 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。
例如,进攻表,我可以看到它在页面上的位置:

我试过几种方法都没成功。例如:

url_off %>%
  html_nodes(".table_outer_container") %>%
  html_nodes("#team_stats")

url_off %>%
  html_nodes(".table_wrapper") %>%
  html_nodes("#team_stats")

当我尝试从该页面提取任何其他表时,这似乎是一个问题。我能得到的唯一两张表是前两张(上面)。我不知道我错在哪里。

eyh26e7m

eyh26e7m1#

我已经解决了。数据都存储为评论,我认为这是我的问题。以下是我如何提取表的,对于任何感兴趣或有类似问题的人:

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()

相关问题