1. 注册和风天气账号
访问 和风天气官网 → 注册账号 → 创建应用获取 API密钥
2. 安装依赖
pip install requests
3. 完整代码实现
import requests
def get_weather(city_name, api_key):
# 和风天气API地址(3天预报)
base_url = "https://devapi.qweather.com/v7/weather/3d"
params = {
"location": city_name, # 支持中文城市名(如"北京")
"key": api_key,
"lang": "zh", # 中文返回
"unit": "m", # 摄氏度单位
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
weather_data = response.json()
# 检查API返回状态
if weather_data.get("code") != "200":
print(f"API错误: {weather_data.get('msg')}")
return None
return weather_data
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
return None
except Exception as err:
print(f"其他错误: {err}")
return None
def display_weather(weather_data):
if not weather_data:
print("无法获取天气数据")
return
# 提取当天天气数据
daily = weather_data["daily"][0]
# print(f"城市: {weather_data['city']}")
print(f"日期: {daily['fxDate']}")
print(f"天气: {daily['textDay']}")
print(f"温度: {daily['tempMin']}℃ ~ {daily['tempMax']}℃")
print(f"风速: {daily['windSpeedDay']} 公里/小时")
print(f"湿度: {daily['humidity']}%")
print(f"紫外线强度: {daily['uvIndex']} 级")
print(f"日出时间: {daily['sunrise']}")
print(f"日落时间: {daily['sunset']}")
if __name__ == "__main__":
# 替换为你的和风天气API密钥
API_KEY = "your api key"
city = input("请输入城市名称(中文): ")
weather_data = get_weather(city, API_KEY)
display_weather(weather_data)
4. 示例输出
(weather) D:\llm\MCP\weather>python hefeng_Test.py
请输入城市名称(中文): 101010100
日期: 2025-03-06
天气: 晴
温度: 1℃ ~ 13℃
风速: 3 公里/小时
湿度: 31%
紫外线强度: 4 级
日出时间: 06:42
日落时间: 18:12
5. 主要特点
-
国内优化
- 服务器位于国内,访问速度快
- 支持中文城市名(如"北京"、“上海市”)
- 符合中国气象标准
-
免费额度
- 开发版:每天 1000 次免费调用
- 商业版需购买(根据需求选择)
-
扩展能力
- 支持7天预报(修改API地址为
v7/weather/7d
) - 支持实时天气(API地址:
v7/weather/now
) - 支持空气质量、生活指数等
- 支持7天预报(修改API地址为
6. 注意事项
-
API密钥安全
- 不要将密钥硬编码在公开代码中
- 建议通过环境变量或配置文件管理
-
城市名称规范
- 使用标准城市名称(如"北京市"、“广州市”)
- 支持经纬度查询(格式:
经度,纬度
)
-
错误处理
- 添加网络超时处理:
requests.get(..., timeout=5)
- 处理城市不存在的情况(检查返回的
code
字段)
- 添加网络超时处理:
开发者文档:https://dev.qweather.com/docs/api/weather/weather-daily-forecast/