从URL读取csv

时间:2018-11-14 15:08:04

标签: r url connection timeout read.csv

我正在使用API​​调用来下载csv格式(无文件名)的Google Analytics(分析)数据。我正在使用以下代码,允许更长的超时时间(此处的URL地址仅是一个非功能性示例)。

fy18url <- "https://supermetrics.com/api/q/......lLF_P"
#Set options and open connection to get data
options(timeout = 300)
conn <- url(fy18url)
open(conn, "r")
gadata <- read.csv(conn, check.names=FALSE)
close(conn)

但是,当我运行此代码时,它将引发错误(第一次),并显示以下消息。

> open(conn, "r")
Error in open.connection(conn, "r") : cannot open the 
connection
In addition: Warning message:
In open.connection(conn, "r") :
InternetOpenUrl failed: 'The operation timed out'
> gadata <- read.csv(conn, check.names=FALSE)
Error in open.connection(file, "rt") : cannot open the 
connection
In addition: Warning message:
In open.connection(file, "rt") :
InternetOpenUrl failed: 'The operation timed out'
> close(conn)

如果我再次运行相同的代码,它将运行正常,并且我会获取所有数据。知道是什么原因造成的吗?

我当时正在考虑使用循环来检查数据并在没有数据的情况下再次运行它,但是想获得一个更简单的解决方案。 谢谢。

1 个答案:

答案 0 :(得分:0)

感谢您的所有建议。这就是现在为我工作的东西。

fy18url <- "https://supermetrics.com/api/q/......."
#Set options
set_config(config(ssl_verifypeer = 0L))
data <- GET(fy18url, timeout(300))
gadata <- read.csv(textConnection(content(data, as = "text")), check.names=FALSE)