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

weather.gov API脚本问题:当前/最高/最低温取值错误求助

解决weather.gov API高低温取值重复问题

你的问题出在混淆了当前观测温度和当日预报高低温的数据源:weather.gov的API里,当前温度来自实时观测接口,而当日最高/最低温来自每日预报接口,两者是不同的返回结构,不能从同一个字段里取。下面是具体修改步骤:

1. 先获取预报接口的端点

weather.gov需要先通过经纬度获取对应的预报URL,添加这段代码:

import requests

# 替换成你的实际经纬度
lat, lon = 37.7749, -122.4194
headers = {"User-Agent": "your-email@example.com"}  # 必填,weather.gov要求标识请求来源

# 获取坐标对应的气象服务端点
point_res = requests.get(f"https://api.weather.gov/points/{lat},{lon}", headers=headers)
point_data = point_res.json()
forecast_url = point_data["properties"]["forecast"]

2. 提取当日最高/最低温

调用预报接口,从返回的时段数据里提取当日白天的最高温和夜间的最低温:

# 获取每日预报数据
forecast_res = requests.get(forecast_url, headers=headers)
forecast_data = forecast_res.json()

high_temp = None
low_temp = None
# 遍历预报时段,匹配当日的白天和夜间数据
for period in forecast_data["properties"]["periods"]:
    if period["name"] == "Today":
        high_temp = period["temperature"]
    elif period["name"] == "Tonight":
        low_temp = period["temperature"]
    # 找到目标数据后可以提前退出循环
    if high_temp and low_temp:
        break

3. 修正当前温度的获取(保留原逻辑但确认字段)

如果你的原脚本是从观测接口取当前温度,确保字段正确:

# 获取实时观测数据(从之前的point数据里取观测站)
stations_url = point_data["properties"]["observationStations"]
stations_res = requests.get(stations_url, headers=headers)
stations_data = stations_res.json()
# 取第一个可用观测站的最新数据
latest_obs_url = stations_data["features"][0]["properties"]["stations"][0] + "/observations/latest"
obs_res = requests.get(latest_obs_url, headers=headers)
obs_data = obs_res.json()

# 提取当前温度(注意转换单位,默认是摄氏度,预报是华氏度的话要转)
current_temp = obs_data["properties"]["temperature"]["value"]
current_temp = round(current_temp * 9/5 + 32)  # 转成华氏度,和预报单位统一

4. 整合到Pushover推送

把正确的三个温度值替换到推送内容里:

# 推送至Pushover
pushover_payload = {
    "token": "你的Pushover应用令牌",
    "user": "你的Pushover用户密钥",
    "message": f"当前温度: {current_temp}°F\n今日最高: {high_temp}°F\n今日最低: {low_temp}°F"
}
requests.post("https://api.pushover.net/1/messages.json", data=pushover_payload)

额外验证技巧

如果不确定字段是否正确,可以先打印返回的结构,确认键名:

# 打印预报时段的字段
print(forecast_data["properties"]["periods"][0].keys())
# 打印观测数据的字段
print(obs_data["properties"].keys())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 14:43:41