问题描述
TLDR :如何查询代码是否出现错误502并刷新直到查询成功?
我正在抓取2016年1月27日至2020年8月15日的每小时数据。从2016年1月27日到2018年5月12日完美运行,在12月5日之后,我不断得到:
Error in read_xml.response(cenace) : Bad Gateway (HTTP 502)
我与检查网页的人联系,他们说这不是普遍问题,“有时”出现502错误,但是如果我直接在网页上进行查询,则很可能会出现502错误。这是网页:
https://ws01.cenace.gob.mx:8082/SWEAIMPEX/SIM/BCA/MDA/2019/07/05/2019/07/07/XML
查询最多允许7天查询
如果第一次遇到错误502,我会刷新网页,并可以在询问的7天内获得XML,但我不知道如何使用我的代码来实现。
到目前为止,我仅按照此question的建议引入了tryCatch
这是我的tryCatch
解决方案代码:
dates <- seq(as.Date("2018/12/06"),as.Date("2020/08/15"),by=1)
spl <- split(dates,cut(seq(NROW(dates)),89))
s <- lapply(spl,`[[`,1)
dates1 <- do.call(c,s)
p <- lapply(spl,tail,n = 1L)
dates2 <- do.call(c,p)
readUrl <- function(url) {
out <- tryCatch(
{
download.file(url,destfile = "scrapedpage.html",quiet=TRUE)
return(1)
},error=function(cond) {
return(0)
},warning=function(cond) {
return(0)
}
)
return(out)
}
BCAINT2 <- NULL
for (i in 1:length(s)){
c(s[i],p[i])
dates1 <- do.call(c,s)
dates2 <- do.call(c,p)
finicio <- as.character(dates1[i],format="%Y/%m/%d")
ffinal <- as.character(dates2[i],format="%Y/%m/%d")
base <- "https://ws01.cenace.gob.mx"
port <- ":8082/SWEAIMPEX/SIM/"
sistema <- "BCA/"
proceso <- "MDA/"
formato <- "XML"
call <- paste(base,port,sistema,proceso,"/",finicio,ffinal,formato,sep= "")
if( readUrl(call)==1) {
download.file(url,quiet=TRUE)
cenace <- GET("scrapedpage.html")
prices <- read_xml(cenace)
parents <-xml_find_all(prices,".//Enlace_Int")
dfs<-lapply(parents,function(node){
clvs <-xml_find_all(node,".//enlace_int") %>% xml_text()
valors <- node %>% xml_find_all(".//Valorv3")
val <- node %>% xml_find_all(".//Valores")
clvs <- clvs[xml_length(val)>0]
#remove cases where the valors nodes have no children nodes
valors <- valors[xml_length(valors)>0]
valornodes <- lapply(valors,function(node){
#get values and names
values <- xml_children(node) %>% xml_text()
names <- xml_children(node) %>% xml_name()
#make data.frame and name the columns
tempdf<- data.frame(t(values),stringsAsFactors = FALSE)
names(tempdf) <- names
tempdf
})
#made data frame with all of results
df<- bind_rows(valornodes)
df<- cbind(clvs,df)
df
})}
q <- do.call(rbind.data.frame,dfs)
BCAINT2 <- rbind(BCAINT2,q)
}
它给了我以下错误:
Error in charToRaw(URL) : argument must be a character vector of length 1
我想解决此错误,但理想情况下,我想解决主要的错误502错误。我对API /报废非常陌生,非常感谢您的帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)