Download file from Internet via R despite popup

Downloading a file from the Internet using R is simple and has been previously reviewed .

My question is about how to get through a pop-up message that does not seem to allow the download to complete. In particular,

download.file(url = "https://www.chicagofed.org/applications/bhc_data/bhcdata_index.cfm?DYR=2012&DQIR=4", destfile = "data/test.zip")

gives me a small garbage file instead of the desired 18 megabyte file that you will get if you go to the website and enter the year 2012and quarter 4manually. I suspect the problem is that, as you can see, when you do this manually, a pop-up window interrupts the download process, asking if you want to save the file or open it. Is there a way to automatically pop-up a window (i.e., through download.file)?

+5
source share
3 answers

This can be done using Selenium, see https://github.com/ropensci/RSelenium .

require(wdman)
require(RSelenium)


selPort <- 4444L
fprof <- makeFirefoxProfile(list(browser.download.dir = "C:\\temp"
                                 ,  browser.download.folderList = 2L
                                 , browser.download.manager.showWhenStarting = FALSE
                                 , browser.helperApps.neverAsk.saveToDisk = "application/zip"))
selServ <- selenium(port = selPort)
remDr <- remoteDriver(extraCapabilities = fprof, port = selPort)
remDr$open(silent = TRUE)
remDr$navigate("https://www.chicagofed.org/applications/bhc_data/bhcdata_index.cfm")
# click year 2012
webElem <- remDr$findElement("name", "SelectedYear")
webElems <- webElem$findChildElements("css selector", "option")
webElems[[which(sapply(webElems, function(x){x$getElementText()}) == "2012" )]]$clickElement()

# click required quarter

webElem <- remDr$findElement("name", "SelectedQuarter")
Sys.sleep(1)
webElems <- webElem$findChildElements("css selector", "option")
webElems[[which(sapply(webElems, function(x){x$getElementText()}) == "4th Quarter" )]]$clickElement()

# click button

webElem <- remDr$findElement("id", "downloadDataFile")
webElem$clickElement()
+6
source

Here is an update of @jdharrison's answer, as it startServerno longer works.

require(wdman)
require(RSelenium)

selPort <- 4444L

fprof <- makeFirefoxProfile(list(browser.download.dir = "C:\\temp"
                                 ,  browser.download.folderList = 2L
                                 , browser.download.manager.showWhenStarting = FALSE
                                 , browser.helperApps.neverAsk.saveToDisk = "application/zip"))

selServ <- selenium(port = selPort)

remDr <- remoteDriver(extraCapabilities = fprof, port = selPort)

Then continue as in the original answer.

0
source

Source: https://habr.com/ru/post/1528184/


All Articles