RVEST select 'drop down' 列表中的一项并提交表单

RVEST select an item from 'drop down' list and submit form

我正在使用 rvest 抓取网站以下载表格中的所有数据。第 1 步正在工作。我没有正确完成第 2 步:

第 1 步:

library(rvest)
library(httr)
url<-'http://www.ahw.gov.ab.ca/IHDA_Retrieval/ihdaData.do'
sess<-html_session(url)
sess %>% follow_link(css='#content > div > p:nth-child(8) > a') -> sess
sess %>% follow_link(css='#content > div > table:nth-child(3) > tbody > tr:nth-child(10) > td > a') -> sess

第 2 步:

pg_form<-html_form(sess)[[2]]
filled_form <-set_values(pg_form, `displayObject.id` = "1006")
d<-submit_form(session=sess, form=filled_form)

我不确定如何提交所选表格。我需要使用 Selenium 而不是 rvest 吗?

不需要使用 RSelenium。您可以使用 rvest 和 httr 抓取这个特定站点,但这有点棘手。您需要了解如何在 http 请求中发送表单。这需要对底层 html 和 Web 浏览器发送的 http 请求进行一些探索。

对于您的情况,表单实际上非常简单。它只有两个字段:一个 command 字段,它总是 "doSelect" 和一个 displayObject.id,它是每个 selection 项目的唯一编号,从 [= html.

中 "option" 标签的 33=] 属性

我们可以通过以下方式查看下拉菜单及其关联的 ID:

library(tidyverse)
library(rvest)
library(httr)

url <- "http://www.ahw.gov.ab.ca/IHDA_Retrieval/"

paste0(url, "ihdaData.do") %>%
GET() %>%
read_html() %>% 
html_node('#content > div > p:nth-child(8) > a') %>%
html_attr("href") %>% 
{paste0(url, .)} %>%
GET() %>%
read_html() %>%
html_node('#content > div > table:nth-child(3) > tbody > tr:nth-child(10) > td > a') %>%
html_attr("href") %>% 
{paste0(url, .)} %>%
GET() %>%
read_html() -> page

pages <- tibble(id = page %>% html_nodes("option") %>% html_attr("value"),
                item = page %>% html_nodes("option") %>% html_text())
pages <- pages[which(pages$item != ""), ]

这为我们提供了页面上可用项目的列表:

pages
#> # A tibble: 8 x 2
#>   id    item                                                                    
#>   <chr> <chr>                                                                   
#> 1 724   Human Immunodeficiency Virus (HIV) Incidence Rate (Age Specific)        
#> 2 723   Human Immunodeficiency Virus (HIV) Incidence Rate (by Geography)        
#> 3 886   Human Immunodeficiency Virus (HIV) Proportion (Ethnicity)               
#> 4 887   Human Immunodeficiency Virus (HIV) Proportion (Exposure Cateogory)      
#> 5 719   Notifiable Diseases - Age-Sex Specific Incidence Rate                   
#> 6 1006  Sexually Transmitted Infections (STI) - Age-Sex Specific Case Counts (P~
#> 7 466   Sexually Transmitted Infections (STI) - Age-Sex Specific Rates of Repor~
#> 8 1110  Sexually Transmitted Infections (STI) - Quarterly Congenital Syphilis C~

现在,如果我们想要 select 第一个,我们只需 post 一个包含正确 url 所需参数的列表,您可以通过查看开发人员来找到浏览器中的控制台(Chrome、Firefox 或 IE 中的 F12)。在这种情况下,它是相对的 url "selectSubCategory.do"

params <- list(command = "doSelect", displayObject.id = pages$id[1])
next_page <- POST(paste0(url, "selectSubCategory.do"), body = params)

现在 next_page 包含您要查找的页面的 html。不幸的是,在这种情况下,它是另一个下拉 selection 页面。

希望按照上述方法,您将能够很好地浏览页面以获取所需的数据。