如何用Python从OpenWeatherMap获取当前及未来2天天气预报
用Python从OpenWeatherMap获取当前天气及未来2天预报
嘿,我帮你理清楚怎么搞定这个需求!其实核心就是两步:发送API请求获取JSON数据,然后解析JSON提取你需要的信息。我一步步给你讲,代码都给你写好,你跟着改就行。
第一步:准备工作
首先确保你安装了requests库——这是Python里发HTTP请求最常用的工具,没装的话打开终端跑:
pip install requests
另外,记得把你的API密钥(就是appid)替换成自己的,还有可以根据需要修改城市参数(比如q=London改成你要查的城市)。
第二步:获取当前天气
用weather API就能拿到当前天气,代码示例如下:
import requests # 替换成你的API密钥和目标城市 api_key = "你的appid" city = "Beijing" current_weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}" try: # 发送请求并解析JSON response = requests.get(current_weather_url) response.raise_for_status() # 如果请求失败,抛出异常 weather_data = response.json() # 提取关键信息 current_temp = round(weather_data["main"]["temp"] - 273.15, 2) # 转成摄氏度 weather_desc = weather_data["weather"][0]["description"] humidity = weather_data["main"]["humidity"] wind_speed = weather_data["wind"]["speed"] # 打印结果 print(f"当前{city}天气:") print(f"温度:{current_temp}℃") print(f"天气描述:{weather_desc}") print(f"湿度:{humidity}%") print(f"风速:{wind_speed}m/s") except requests.exceptions.RequestException as e: print(f"请求出错了:{e}")
关于JSON解析的小说明:
response.json()会把返回的JSON字符串转成Python的字典/列表,你可以像操作普通字典一样取值:
weather_data["main"]是包含温度、湿度等信息的子字典weather_data["weather"]是一个列表,里面的第一个元素就是当前天气的详细描述(因为有时候会有多个天气状况,但一般取第一个就行)
第三步:获取未来2天的天气预报
这里要用到forecast API,它返回每3小时一次的预报数据。我们需要筛选出未来48小时内的结果,代码如下:
import requests from datetime import datetime, timedelta api_key = "你的appid" city = "Beijing" forecast_url = f"http://api.openweathermap.org/data/2.5/forecast?q={city}&appid={api_key}" try: response = requests.get(forecast_url) response.raise_for_status() forecast_data = response.json() # 计算未来2天的截止时间 end_time = datetime.now() + timedelta(days=2) print(f"\n{city}未来2天天气预报:") # 遍历所有预报项 for item in forecast_data["list"]: # 把API返回的时间字符串转成datetime对象 forecast_time = datetime.strptime(item["dt_txt"], "%Y-%m-%d %H:%M:%S") # 只保留未来2天内的预报 if forecast_time <= end_time: temp = round(item["main"]["temp"] - 273.15, 2) desc = item["weather"][0]["description"] print(f"{forecast_time.strftime('%Y-%m-%d %H:%M')}:{temp}℃,{desc}") except requests.exceptions.RequestException as e: print(f"请求出错了:{e}")
这里的关键点:
forecast_data["list"]是所有预报项的列表,每个元素对应一个3小时时段的天气- 我们用
datetime模块把API返回的时间字符串转成可比较的时间对象,过滤出未来2天内的结果 - 如果只想按天分组显示,你可以额外处理日期,把同一天的预报归到一起
常见问题排查
如果之前尝试失败,可能是这些原因:
- API密钥错误:检查你的
appid是否正确,有没有在OpenWeatherMap后台激活 - 请求参数错误:比如城市名拼写错误,或者没有加
q=这样的参数前缀 - 网络问题:确保你的程序能正常访问外部网络
- JSON取值错误:比如拼写错了键名(比如把
main写成Main,JSON的键是区分大小写的)
内容的提问来源于stack exchange,提问作者user_123




