You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R调用API获取NWS近7天降水数据?解决最近2天数据缺失问题

问题

正在开发一款Shiny应用,用于展示当日起未来及过去7天的预报和累计降水数据。已通过NWS API成功获取预报降水数据,但获取过去数据时遇到问题:使用NCEI的CDO API无法获取最近两天的数据。

限制条件与尝试方向

  • 任务限定必须使用NOAA数据,虽然Open-Meteo等API更易用;
  • NWS官网可查看近7天历史数据,但未找到对应API,官网引导至NCEI获取归档数据;
  • 尝试过网页爬取该页面,但经验不足,希望获得更简便的解决方案。

现有代码片段

# 加载必要库
library(httr)
library(jsonlite)

# 定义API密钥(需自行从NOAA获取)
api_key <- "Your API Key" # 运行此代码需要API密钥

# 定义目标位置经纬度
latitude <- "40.7128"  # 纽约市纬度
longitude <- "-74.0060"  # 纽约市经度

# 定义API端点
endpoint <- "https://www.ncdc.noaa.gov/cdo-web/api/v2/data"

# 定义API请求参数
parameters <- list(
  datasetid = "GHCND",        # 日汇总数据集ID
  datatypeid = "PRCP",        # 降水量数据类型ID
  stationid = "GHCND:USW00094728",  # 纽约中央公园气象站ID
  startdate = Sys.Date()-7,   # 数据起始日期(过去7天)
  enddate = Sys.Date(),       # 数据结束日期(当日)
  units = "metric",           # 数据单位(公制或英制)
  limit = 1000,               # 单次请求返回记录上限
  offset = 1                  # 分页偏移量
)

# 发送API请求
response <- GET(
  url = endpoint,
  query = parameters,
  add_headers(.headers = c("token" = api_key))
)

# 检查请求是否成功
if (http_error(response)) {
  stop("HTTP错误: ", http_status(response)$reason)
} else {
  # 解析JSON响应
  data <- content(response, "parsed")
  
  # 提取相关信息(如降水量数值)
  # 示例:如果响应包含日降水量数据,可按如下方式获取
  daily_precipitation <- data$value
  
  # 打印或进一步处理提取的数据
  print(daily_precipitation)
}

解决方案:用NWS Gridpoint API补全近期数据

NCEI的CDO API存在数据归档延迟(通常1-2天),无法获取最新的历史数据,但可通过NWS Gridpoint API获取站点的实时/近期观测数据,完美覆盖过去7天的时间范围:

1. 获取Gridpoint服务端点

先通过经纬度定位到对应气象网格的API端点:

# 获取Gridpoint端点
point_response <- GET(paste0("https://api.weather.gov/points/", latitude, ",", longitude))
point_data <- content(point_response, "parsed")
grid_endpoint <- point_data$properties$forecastGridData

2. 拉取近期降水观测

调用Gridpoint的观测接口,指定时间范围获取降水数据:

# 获取过去7天的观测数据
obs_response <- GET(paste0(grid_endpoint, "/observations"), 
                    query = list(start = Sys.Date()-7, end = Sys.Date()))
obs_data <- content(obs_response, "parsed")

# 提取降水量数据(可根据需求选择不同时间粒度字段)
precip_observations <- lapply(obs_data$features, function(x) {
  list(
    date = x$properties$timestamp,
    precip_total = x$properties$values$precipitationLast6Hours
  )
})

# 转换为数据框便于后续处理
precip_df <- do.call(rbind, lapply(precip_observations, as.data.frame))

3. 数据整合

将Gridpoint获取的最新2天数据,与CDO API返回的更早历史数据合并,即可得到完整的过去7天降水数据集。

备选:简化网页爬取方案(仅作参考)

如果需要爬取NWS历史数据页面,可使用rvest库简化操作(需遵守网站robots协议):

library(rvest)
url <- "https://www.weather.gov/wrh/timeseries?site=MOIC1"
page <- read_html(url)
# 根据页面结构提取降水数值(需根据实际页面调整选择器)
precip_values <- page %>% html_nodes(".precip-row .value") %>% html_text()

内容的提问来源于stack exchange,提问作者Nikole Vannest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:26:06