使用 r 导航和抓取带有下拉 html 表单的网页

Using r to navigate and scrape a webpage with drop down html forms

我正在尝试从 http://www.footballoutsiders.com/stats/snapcounts 抓取数据,但我无法更改网站下拉框中的字段("team"、"week"、"position",和 "year")。我尝试用 rvest 抓取与 team = "ALL"、week= "1"、pos = "All" 和 year= "2015" 关联的 table。

url <- "http://www.footballoutsiders.com/stats/snapcounts"
pgsession <- html_session(url)
pgform <-html_form(pgsession)[[3]]
filled_form <-set_values(pgform,
            "team" = "ALL",
            "week" = "1",
            "pos"  = "ALL",
            "year" = "2015"             
 )

 submit_form(session=pgsession,form=filled_form, POST=url)

 y <- read_html("http://www.footballoutsiders.com/stats/snapcounts")

 y <- y %>%
    html_nodes("table") %>%
    .[[2]] %>%
    html_table(header=TRUE)

这段代码returnstable关联了下拉框里的默认变量是team="ALL",week="20",pos="QB",和 year= "2015" 这是一个只包含 11 个观测值的数据框。如果它真的改变了字段,它会返回一个包含 1,695 个观察值的数据框。

您可以捕获提交表单时产生的会话,并将该会话用作 html_nodes 的输入:

d <- submit_form(session=pgsession, form=filled_form)

y <- d %>%
    html_nodes("table") %>%
    .[[2]] %>%
    html_table(header=TRUE)

dim(y)
#[1] 1695   11

否则,如果您使用 read_html(url),您正在阅读原始页面。