用Python构建一个天气API集成

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. 主要特点

  1. 国内优化

    • 服务器位于国内,访问速度快
    • 支持中文城市名(如"北京"、“上海市”)
    • 符合中国气象标准
  2. 免费额度

    • 开发版:每天 1000 次免费调用
    • 商业版需购买(根据需求选择)
  3. 扩展能力

    • 支持7天预报(修改API地址为 v7/weather/7d
    • 支持实时天气(API地址:v7/weather/now
    • 支持空气质量、生活指数等

6. 注意事项

  1. API密钥安全

    • 不要将密钥硬编码在公开代码中
    • 建议通过环境变量或配置文件管理
  2. 城市名称规范

    • 使用标准城市名称(如"北京市"、“广州市”)
    • 支持经纬度查询(格式:经度,纬度
  3. 错误处理

    • 添加网络超时处理:requests.get(..., timeout=5)
    • 处理城市不存在的情况(检查返回的 code 字段)

开发者文档:https://dev.qweather.com/docs/api/weather/weather-daily-forecast/

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值