Python 天气查询程序(调用和风天气API,极简版)
核心实现根据城市查实时天气,需先在和风天气开放平台申请免费API Key,步骤简单且有免费额度。
完整代码import requests
# 配置信息(替换为你自己的API Key和城市ID)
API_KEY = "你的和风天气API Key"
CITY_ID = "101010100" # 示例:北京的城市ID,可在和风平台查询
BASE_URL = "https://devapi.qweather.com/v7/weather/now"
def get_weather():
"""获取实时天气"""
params = {
"key": API_KEY,
"location": CITY_ID,
"lang": "zh-CN",
"unit": "m" # 公制单位(摄氏度)
}
try:
response = requests.get(BASE_URL, params=params, timeout=10)
response.raise_for_status() # 抛出HTTP请求错误
weather_data = response.json()
# 解析核心天气数据
if weather_data["code"] == "200":
now = weather_data["now"]
city = weather_data["location"]["name"]
temp = now["temp"] # 实时气温
feels_like = now["feelsLike"] # 体感温度
condition = now["text"] # 天气状况(晴/雨等)
wind = now["windDir"] + now["windScale"] + "级" # 风向风力
# 打印结果
print(f"【{city}实时天气】")
print(f"天气状况:{condition}")
print(f"实时气温:{temp}℃(体感{feels_like}℃)")
print(f"风向风力:{wind}")
else:
print(f"查询失败:{weather_data['msg']}")
except requests.exceptions.RequestException as e:
print(f"网络错误:{e}")
except KeyError:
print("数据解析失败,可能是API Key或城市ID错误")
if __name__ == "__main__":
get_weather()
快速使用步骤
1. 安装依赖: pip install requests
2. 去和风天气开放平台注册,申请免费版API Key(个人开发足够用)
3. 在和风平台查询目标城市的城市ID(如上海101020100),替换代码中的 CITY_ID
4. 替换 API_KEY 为你申请的密钥,运行代码即可。
扩展功能(可自行添加)
1. 支持城市名称模糊查询(调用和风的地理编码API,根据名称查城市ID)
2. 添加未来7天预报(修改API接口为 v7/weather/7d )
3. 增加空气质量、湿度、降水概率解析(返回数据中均包含)
4. 制作简单GUI界面(用 tkinter / PyQt ,适合可视化)
备用方案(无API版,爬取简易天气)
若不想申请API,可使用 BeautifulSoup 爬取免费天气网页(注意遵守网站robots协议),核心依赖: pip install requests beautifulsoup4 ,适合新手练手。