使用R"点击"网页上的下载文件按钮

abe*_*bet 7 post r httr rselenium

我试图使用这个网页http://volcano.si.edu/search_eruption.cfm来抓取数据.有两个下拉框要求过滤数据.我不需要过滤数据,因此我将其留空并继续单击" 搜索喷发 " 进入下一页.

然而,我注意到,结果表只包含少量列(仅5个),而不是它应该具有的总列数(总共24个).但是,如果单击"将结果下载到Excel "按钮并打开下载的文件,则所有24列都将在那里.这就是我需要的.

所以,看起来这已经从一次刮痧练习(使用httr和rvest)转变为更困难的事情.但是,我对如何使用R 实际"点击""将结果下载到Excel "按钮感到困惑.我的猜测是我将不得不使用RSelenium,但这里是我的代码试图使用带有POST的httr以防万一任何一个善良的人都可以找到一种更简单的方式.我也尝试过使用gdata,data.table,XML等无济于事,这可能只是用户错误的结果.

此外,知道无法右键单击下载按钮以显示URL可能会有所帮助.

url <- "http://volcano.si.edu/search_eruption_results.cfm"

searchcriteria <- list(
    eruption_category = "",
    country = ""
)

mydata <- POST(url, body = "searchcriteria")
Run Code Online (Sandbox Code Playgroud)

在我的浏览器中使用Inspector,我能够看到两个过滤器是"eruption_category"和"country",两者都是空白的,因为我不需要任何过滤数据.

最后,似乎上面的代码将使我进入只有5列的表的页面.但是,我仍然无法在下面的代码中使用rvest来刮掉这个表(使用SelectorGadget只刮一列).最后,这部分并不重要,因为正如我上面所说,我需要所有24列,而不仅仅是这些5列.但是,如果你发现我在下面做的任何错误,我将不胜感激.

Eruptions <- mydata %>%
    read_html() %>%
    html_nodes(".td8") %>%
    html_text()
Eruptions
Run Code Online (Sandbox Code Playgroud)

感谢您提供任何帮助.

hrb*_*str 8

只需模仿POST它的作用:

library(httr)
library(rvest)
library(purrr)
library(dplyr)

POST("http://volcano.si.edu/search_eruption_results.cfm",
     body = list(bp = "", `eruption_category[]` = "", `country[]` = "", polygon = "",  cp = "1"),
     encode = "form") -> res

content(res, as="parsed") %>%
  html_nodes("div.DivTableSearch") %>%
  html_nodes("div.tr") %>%
  map(html_children) %>%
  map(html_text) %>%
  map(as.list) %>%
  map_df(setNames, c("volcano_name", "subregion", "eruption_type",
                     "start_date", "max_vei", "X1")) %>%
  select(-X1)
## # A tibble: 750 × 5
##    volcano_name            subregion      eruption_type  start_date
##           <chr>                <chr>              <chr>       <chr>
## 1   Chirinkotan        Kuril Islands Confirmed Eruption 2016 Nov 29
## 2   Zhupanovsky  Kamchatka Peninsula Confirmed Eruption 2016 Nov 20
## 3       Kerinci              Sumatra Confirmed Eruption 2016 Nov 15
## 4       Langila          New Britain Confirmed Eruption  2016 Nov 3
## 5     Cleveland     Aleutian Islands Confirmed Eruption 2016 Oct 24
## 6         Ebeko        Kuril Islands Confirmed Eruption 2016 Oct 20
## 7        Ulawun          New Britain Confirmed Eruption 2016 Oct 11
## 8      Karymsky  Kamchatka Peninsula Confirmed Eruption  2016 Oct 5
## 9        Ubinas                 Peru Confirmed Eruption  2016 Oct 2
## 10      Rinjani Lesser Sunda Islands Confirmed Eruption 2016 Sep 27
## # ... with 740 more rows, and 1 more variables: max_vei <chr>
Run Code Online (Sandbox Code Playgroud)

我认为可以推断出“Excel”部分,但如果不是:

POST("http://volcano.si.edu/search_eruption_excel.cfm", 
     body = list(`eruption_category[]` = "", 
                 `country[]` = ""), 
     encode = "form",
     write_disk("eruptions.xls")) -> res
Run Code Online (Sandbox Code Playgroud)

  • 添加它(我认为它很容易推断) (2认同)