用 rvest 抓取——数据有 <table> 标签但用 html_table() 找不到

Scraping with rvest -- data has <table> tag but not found with html_table()

我正试图从 this site 的 table 中抓取一些高中体育成绩,但是 rvest html_table() 函数 returns 没有...只是一个空列表。数据似乎显然位于 table 标记内,所以我认为这会非常简单,但事实并非如此。

html_data <- read_html("https://highschoolsports.nj.com/boysbasketball/schedule/2020/01/09")
html_data %>% html_table(html_data)

任何关于如何提取此 table 的帮助或建议将不胜感激!

您看到的 table 是使用 javascript 动态构建的。该页面发送一个 json 文件的 xhr 请求,该文件包含 table 中的所有数据(加上您看不到的更多数据)。

你需要做的是请求json文件,解析它并提取你想要的元素。以下脚本将为您完成:

library(tidyverse)
library(httr)
library(rjson)

"https://highschoolsports.nj.com/siteapi/games/schedule" %>%
modify_url( query = list( viewStart      = "1/9/2020",
                          sportId        = "15",
                          schoolId       = "",
                          scheduleYearId = ""))          %>%
GET()                                                    %>%
content("text")                                          %>%
fromJSON()                                               %>%
`[[`("games")                                            %>%
lapply(function(x) data.frame(x$gameDate, x$name))       %>%
{do.call("rbind", .)}                                    %>%
as_tibble                                                 ->
result

print(result)
#> # A tibble: 324 x 2
#>    x.gameDate          x.name                                            
#>    <fct>               <fct>                                             
#>  1 2020-01-09T00:00:00 Manville (43) at Pingry (77)                      
#>  2 2020-01-09T00:00:00 Eastern (41) at Cherokee (54)                     
#>  3 2020-01-09T00:00:00 Woodbridge (31) at Colonia (54)                   
#>  4 2020-01-09T00:00:00 Phillipsburg (64) at Bridgewater-Raritan (71)     
#>  5 2020-01-09T05:30:00 Asbury Park (44) at Point Pleasant Beach (50)     
#>  6 2020-01-09T07:00:00 Montclair Immaculate (78) at Newark East Side (49)
#>  7 2020-01-09T15:45:00 Christian Brothers (67) at Howell (62)            
#>  8 2020-01-09T16:00:00 West Caldwell Tech (59) at Weequahic (60)         
#>  9 2020-01-09T16:00:00 Scotch Plains-Fanwood (20) at Westfield (55)      
#> 10 2020-01-09T16:00:00 Summit (59) at Cranford (44)                      
#> # ... with 314 more rows

如果你在 json 中挖掘,很容易得到个人分数等,所以如果你想要 table 在数据框列中包含这些数据,你可以更改函数在 lapply 命令中 select 您想要作为数据框中条目的那些。