基于公开接口的 Python 气象数据采集方案
基于 OpenWeatherMap 的数据获取
在命令行环境下构建轻量级天气查询工具时,HTTP 请求库是核心组件。以下示例展示了如何调用 OpenWeatherMap 的公共服务接口,并处理返回的 JSON 数据。代码中通过设置参数明确指定了单位为摄氏度以及语言环境为简体中文。
import requests
from typing import Dict, Any
def fetch_metric_temp(loc_query: str, secret: str) -> Dict[str, Any]:
"""
从 OpenWeatherMap 抓取特定城市的基础气象信息
"""
base_url = "https://api.openweathermap.org/data/2.5/weather"
payload = {
"q": loc_query,
"appid": secret,
"units": "metric",
"lang": "zh_CN"
}
try:
resp = requests.get(base_url, params=payload, timeout=8)
resp.raise_for_status()
content = resp.json()
if content.get("cod") == 200:
return {
"location": loc_query,
"condition": content["weather"][0]["description"],
"temp_c": content["main"]["temp"],
"humidity": content["main"]["humidity"],
"wind_spd": content["wind"].get("speed", 0)
}
except requests.exceptions.RequestException as err:
print(f"网络通信异常:{err}")
except KeyError:
print("JSON 结构解析失败")
return {}
if __name__ == "__main__":
user_loc = input("输入目标城市拼音或英文名:").strip()
user_key = input("输入验证令牌 (API Token):").strip()
result = fetch_metric_temp(user_loc, user_key)
if result:
print(f"[状态] 成功查询到 {user_loc}")
print(f"- 现象:{result['condition']}")
print(f"- 温度:{result['temp_c']}°C")
print(f"- 湿度:{result['humidity']}%")
print(f"- 风力:{result['wind_spd']} m/s")
else:
print("未能获取有效数据")
调用百度地图气象服务
国内开发者也可以使用百度开放平台提供的 telematics 接口来获取本地化天气信息。此方案支持直接使用中文城市名称作为定位参数,无需进行拼音转换。
import requests
import json
def extract_baidu_climate(city_input: str, key: str):
"""
解析百度地图天气接口响应数据
"""
target_api = "http://api.map.baidu.com/telematics/v3/weather"
query_params = {
"location": city_input,
"output": "json",
"ak": key
}
try:
req = requests.get(target_api, params=query_params, timeout=10)
raw_data = req.json()
# 验证返回码是否合规
if raw_data.get("status") != 0:
print(f"业务层错误码:{raw_data.get('message', '未知')}")
return
items = raw_data.get("results", [])
if not items:
print("该地区无可用天气记录")
return
# 取第一条结果进行处理
record = items[0]
current_place = record.get("currentCity")
forecast_list = record.get("weather_data", [])
print(f"📍 当前区域:{current_place}")
if forecast_list and len(forecast_list) > 0:
day_forecast = forecast_list[0]
print(f"🌡 今日气温:{day_forecast.get('temperature')}")
print(f"☁️ 天气状况:{day_forecast.get('weather')}")
print(f"📅 预报日期:{day_forecast.get('date')}")
except requests.RequestException:
print("连接服务器超时或服务不可达")
if __name__ == "__main__":
# 提示用户注意 API Key 的权限范围配置
city_str = input("请输入中文城市名:")
ak_code = input("请输入百度 AK:")
extract_baidu_climate(city_str, ak_code)
开发注意事项
在使用上述接口前,需前往对应平台的开发者控制台完成密钥申请流程。对于生产环境部署,建议将敏感凭证(如 API Key 或 Access Key)配置在环境变量中,避免硬编码在源代码里导致泄露风险。此外,不同服务商均设有每日调用配额限制,频繁请求可能导致 IP 被封禁或账号限流,需在代码中加入适当的重试机制或缓存策略以优化资源消耗。