如何用R通过API自动提取Risk Data Hub的罗马尼亚风险数据?
问题描述
需从Risk Data Hub提取罗马尼亚的风险数据,手动操作可选择国家、区域、资产类型(如住宅)、灾害类型(如河流洪水)、时间范围后下载对应报告。因站点数据持续更新,需实现自动化获取方案。
已找到该站点的API门户,且用R代码成功下载了多边形数据,但无法找到手动下载的风险数据对应的API接口,现需修改现有R代码以实现该风险数据的自动化提取。
现有R代码
library(httr) library(jsonlite) library(geojsonsf) library(leaflet) jrc_codes <- readxl::read_excel("C:/Users/CG14328/Desktop/adm_unit_codes3.xlsx") get_new_token <- function() { token_url <- "https://drmkc.jrc.ec.europa.eu/risk-data-hub-api/ " response <- GET( url = token_url, query = list(key = "demo_key"), add_headers(apikey = "demo_api_key") ) if (status_code(response) != 200) { stop("Failed to get token: ", content(response, "text")) } message("Successfully obtained new token.") content(response, "text") } safe_geojson_sf <- function(geojson) { tryCatch( geojsonsf::geojson_sf(geojson), error = function(e) { message("Error converting GeoJSON to sf: ", e$message) NULL } ) } division_url <- "https://drmkc.jrc.ec.europa.eu/risk-data-hub-api/collections/admin/division/items" results <- list() batch_size <- 5 num_batches <- ceiling(length(jrc_codes$Code) / batch_size) for (batch_num in 1:num_batches) { repeat { token <- tryCatch( get_new_token(), error = function(e) { message("Failed to obtain token: ", e$message, ". Retrying in 60 seconds...") Sys.sleep(60) NULL } ) if (!is.null(token)) break } start_index <- (batch_num - 1) * batch_size + 1 end_index <- min(batch_num * batch_size, length(jrc_codes$Code)) admin_codes <- gsub("\"", "", jrc_codes$Code[start_index:end_index]) for (code in admin_codes) { division_query_params <- list( lang = "en-US", admin_unit_code = code ) response <- GET( url = division_url, add_headers(Authorization = paste("Bearer", token)), query = division_query_params ) if (status_code(response) == 200) { data <- tryCatch( content(response, "parsed"), error = function(e) { message("Failed to parse response for code ", code, ": ", e$message) NULL } ) if (!is.null(data) && is.list(data) && !is.null(data$features) && length(data$features) > 0) { results[[code]] <- data } else { message("No valid features returned for code: ", code) } } else { message("Failed to get data for code: ", code, " with status: ", status_code(response)) message("Response content: ", content(response, "text", encoding = "UTF-8")) } } Sys.sleep(60) } combined_data <- lapply(results, function(res) safe_geojson_sf(toJSON(res, auto_unbox = TRUE))) final_data <- do.call(rbind, combined_data[!sapply(combined_data, is.null)]) leaflet(final_data) %>% addTiles() %>% addPolygons(color = "#444444", weight = 1, smoothFactor = 0.5, opacity = 1.0, fillOpacity = 0.5)
内容的提问来源于stack exchange,提问作者Tech.Zaur
相关产品推荐
相关产品推荐

