我尝试下载一个文件,为了从服务器获取它,我需要同时发送数据。在命令行上使用 curl,它可以正常工作:
curl "https://www.ishares.com/us/product-screener-download.dl" --data "productView=ishares&portfolios=239561-239855"
不幸的是,我没有让它与 R 一起工作。我尝试使用download.file,download.file与libcurl,curl_download和httr。(带有 curl 或 wget 的 download.file 不起作用,因为我在窗口机器上。
我尝试过但无法使用 curl 的:
library("curl")
handle <- new_handle()
handle_setopt(handle, customrequest = "POST")
handle_setform(handle, productView="ishares",portfolios="239561-239855")
curl_download("https://www.ishares.com/us/products/etf-product-list", "./data/ishares-us-etf.xls", handle=handle)
我尝试过但无法使用 httr 的内容:
library(httr)
POST("https://www.ishares.com/us/products/etf-product-list", body = list(productView="ishares",portfolios="239561-239855"))
在与小提琴手一起找到一些东西后,我发现我需要使用postfield发送数据,然后一切正常。
library("curl")
handle <- new_handle()
handle_setopt(handle, customrequest = "POST")
handle_setopt(handle, postfields='productView=ishares&portfolios=239561-239855')
curl_download("https://www.ishares.com/us/product-screener-download.dl", "./data/ishares-us-etf.xls", handle=handle)
您应该在httr::POST()
中使用正确的URL和encode = "form"
。
基于@leo答案的httr
解决方案:
library(httr)
POST("https://www.ishares.com/us/product-screener-download.dl",
body = list(productView = "ishares", portfolios = "239561-239855"),
encode = "form", write_disk("/tmp/ishares-us-etf.xls"))
#> Response [https://www.ishares.com/us/product-screener-download.dl]
#> Date: 2016-02-08 06:52
#> Status: 200
#> Content-Type: application/vnd.ms-excel;charset=UTF-8
#> Size: 13.6 kB
#> <ON DISK> /tmp/ishares-us-etf.xls
head(readLines(file_path), 5)
#> [1] "<?xml version="1.0"?>"
#> [2] "<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">"
#> [3] "<Styles>"
#> [4] "<Style ss:ID="Default">"
#> [5] "<Alignment Horizontal="Left"/>"
这不会做这项工作吗?
URL <- "https://www.ishares.com/us/products/etf-product-list"
values <- list(productView="ishares", portfolios="239561-239855")
POST(URL, body = values)
r <- GET(URL, query = values)
x <- content(r)