【问题标题】:Downloading large files with R/RCurl efficiently使用 R/RCurl 高效下载大文件
【发布时间】:2013-01-20 16:06:45
【问题描述】:

我看到很多用RCurl下载二进制文件的例子都是这样的:

library("RCurl")
curl = getCurlHandle()
bfile=getBinaryURL (
        "http://www.example.com/bfile.zip",
        curl= curl,
        progressfunction = function(down, up) {print(down)}, noprogress = FALSE
)
writeBin(bfile, "bfile.zip")
rm(curl, bfile)

如果下载量很大,我想最好将它同时写入存储介质,而不是全部在内存中获取。

在 RCurl 文档中,有一些示例可以按块获取文件并在下载文件时对其进行操作,但它们似乎都称为文本块。

你能举个例子吗?

更新

一位用户建议对二进制文件使用 R 原生 download filemode = 'wb' 选项。

在许多情况下,本机函数是一种可行的替代方案,但在许多用例中,本机函数不适用(https、cookie、表单等),这就是 RCurl 存在的原因。

【问题讨论】:

  • download.file 没有读入 RAM .. 你能提供一个示例文件来下载 download.file 不起作用吗? :)

标签: r curl rcurl


【解决方案1】:

这是工作示例:

library(RCurl)
#
f = CFILE("bfile.zip", mode="wb")
curlPerform(url = "http://www.example.com/bfile.zip", writedata = f@ref)
close(f)

它将直接下载到文件中。返回值将是(而不是下载的数据)请求的状态(0,如果没有错误发生)。

提及CFILE 在 RCurl 手册上有点简洁。希望将来它会包含更多详细信息/示例。

为方便起见,将相同的代码打包为函数(并带有进度条):

bdown=function(url, file){
    library('RCurl')
    f = CFILE(file, mode="wb")
    a = curlPerform(url = url, writedata = f@ref, noprogress=FALSE)
    close(f)
    return(a)
}

## ...and now just give remote and local paths     
ret = bdown("http://www.example.com/bfile.zip", "path/to/bfile.zip")

【讨论】:

  • 在 BATCH 中运行 R 时,是否有任何理由工作?
  • 如果在包中使用此解决方案,您可能需要将close(f) 更改为RCurl::close(f),否则您可能会遇到找不到CFILE 的关闭方法的错误。
【解决方案2】:

嗯.. 使用 mode = 'wb' :) .. 运行它并跟随我的 cmets。

# create a temporary file and a temporary directory on your local disk
tf <- tempfile()
td <- tempdir()

# run the download file function, download as binary..  save the result to the temporary file
download.file(
    "http://sourceforge.net/projects/peazip/files/4.8/peazip_portable-4.8.WINDOWS.zip/download",
    tf ,
    mode = 'wb' 
)

# unzip the files to the temporary directory
files <- unzip( tf , exdir = td )

# here are your files
files

【讨论】:

  • 它有效,谢谢。我没有检查'wb',因为在没有其他网站的情况下它也可以工作。例如。 download.file("http://www.nirsoft.net/utils/gdiview.zip", "gdiview.zip"),所以我把它归结为sf.net的重定向方式。现在,由于我使用 EMACS ESS,我必须解决将不在控制台上的进度条显示为 RCurl,而是使用 GUI 小部件的问题。
  • @antonio 将其标记为已接受并编辑标题,因为答案不涉及 RCurl :P
  • 虽然你的是一个不错的选择,但我认为研究 RCurl 二进制下载(R_curl_write_binary_data 等)仍然很有趣。
  • 这可能很有趣,但这不是您提出的问题的答案;)
  • 我写道:“在 RCurl 文档中有一些按块获取文件的示例 [...],但它们似乎都提到了 文本块。你能举一个 [for binary ones] 的工作示例吗?”你让我给你一个download.file的例子,我做到了。你让我把它移到这个问题上,我做到了。我再次感谢您的“wb”提示,但我曾经而且我仍然对 RCurl 感兴趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多