使用 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
)?
这可以使用 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()
请在您的 Firefox 中安装 Firebug 插件,看看访问并配置 Web 请求时会发生什么。 IMO 认为 2013 年第一季度的要求要复杂得多,需要详细分析。它使用 cookie 并启动一些脚本操作...
我也遇到了同样的问题。我可以重新打开这个问题并请求一些建议吗?谢谢!