从互联网上通过R下载文件,即使出现弹窗

5

使用R从互联网下载文件很容易,之前已经有人讨论过这个问题

我的问题是如何跳过弹出窗口消息,以便顺利下载。具体地说,

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

给我的只是一小段垃圾文件,而不是如果手动进入网站并输入年份2012和季度4时可以得到的18兆字节文件。我怀疑问题在于当您手动下载时,弹出窗口会打断下载过程,询问是否保存文件或打开它。有没有办法通过download.file自动跳过弹出窗口呢?
2个回答

6
这可以通过Selenium实现,参见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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接