我正在尝试从this site上的表格中抓取一些高中体育成绩,但是rvest html_table()函数什么也不返回……只是一个空列表。数据似乎显然位于 table 标记内,所以我认为这很简单,但事实并非如此。
html_data <- read_html("https://highschoolsports.nj.com/boysbasketball/schedule/2020/01/09")
html_data %>% html_table(html_data)
任何有关如何提取此表的帮助或建议,将不胜感激!
答案 0 :(得分:4)
您看到的表是使用javascript动态生成的。该页面向xhr请求发送一个json文件,该文件包含表中的所有数据(还有很多您看不到的数据)。
您需要做的是请求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中进行挖掘,很容易获得各个分数等,因此,如果要在数据框架列中使用包含此数据的表,则可以更改lapply
命令中的函数以选择您想要在数据框中输入的内容。