Python中通过get请求获取api.open-meteo.com网站的天气数据

Python中通过get请求获取api.open-meteo.com网站的天气数据

C++中使用cpp-httplib和nlohmann_json库实现http请求获取天气数据Nodejs通过get请求获取api.open-meteo.com网站的天气数据使用Java通过get请求获取api.open-meteo.com网站的天气数据,我们再使用Python语言实现对应功能,看起来代码量少了很多。

以下是使用 Python 发送 HTTP GET 请求以获取 api.open-meteo.com 网站天气数据的示例代码:


Python示例代码

python 复制代码
import requests

def get_weather():
    # API URL
    api_url = "http://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": 37.8136,  # 纬度
        "longitude": 144.9631,  # 经度
        "current_weather": "true"  # 当前天气
    }

    try:
        # 发送 GET 请求
        response = requests.get(api_url, params=params)

        # 检查响应状态码
        if response.status_code == 200:
            # 打印天气数据
            print("Weather Data:")
            print(response.json())
        else:
            print(f"GET request failed with status code: {response.status_code}")
    except Exception as e:
        print(f"An error occurred: {e}")

# 调用函数
if __name__ == "__main__":
    get_weather()

说明

  1. requests 模块:

    • 使用 requests 模块发送 HTTP GET 请求。
    • params 参数用于传递查询参数(如纬度、经度和当前天气)。
  2. API URL:

    • http://api.open-meteo.com/v1/forecast 是天气 API 的基础 URL。
    • 查询参数包括:
      • latitude:纬度。
      • longitude:经度。
      • current_weather:是否获取当前天气数据。
  3. 响应处理:

    • 如果状态码为 200,解析并打印 JSON 响应。
    • 如果状态码不是 200,打印错误信息。
  4. 异常处理:

    • 捕获网络错误或其他异常,并打印错误信息。

运行代码

  1. 安装 requests 模块

    如果尚未安装 requests,请运行以下命令:

    bash 复制代码
    pip install requests
  2. 保存文件

    将代码保存为 get_weather_data.py

  3. 运行脚本

    在终端中运行:

    bash 复制代码
    python get_weather_data.py

示例输出

plaintext 复制代码
Weather Data: {'latitude': 37.8125, 'longitude': 37.8125, 'generationtime_ms': 0.05257129669189453, 'utc_offset_seconds': 0, 'timezone': 'GMT', 'timezone_abbreviation': 'GMT', 'elevation': 1031.0, 'current_weather_units': {'time': 'iso8601', 'interval': 'seconds', 'temperature': '°C', 'windspeed': 'km/h', 'winddirection': '°', 'is_day': '', 'weathercode': 'wmo code'}, 'current_weather': {'time': '2025-11-01T13:30', 'interval': 900, 'temperature': 20.8, 'windspeed': 1.1, 'winddirection': 288, 'is_day': 1, 'weathercode': 2}}

注意事项

  1. 确保你的网络可以访问 http://api.open-meteo.com

  2. 如果需要更复杂的功能(如 POST 请求或认证),可以扩展代码。

  3. 如果需要解析 JSON 数据,可以直接访问字典键。例如:

    python 复制代码
    data = response.json()
    temperature = data["current_weather"]["temperature"]
    print(f"Current temperature: {temperature}°C")
相关推荐
云和数据.ChenGuang6 小时前
Uvicorn 是 **Python 生态中用于运行异步 Web 应用的 ASGI 服务器**
服务器·前端·人工智能·python·机器学习
Hello.Reader6 小时前
PyFlink Table API / DataStream API / UDF / 依赖管理 / 运行时模式一篇打通(含示例代码与避坑)
python·flink
DYS_房东的猫6 小时前
《 C++ 零基础入门教程》第3章:结构体与类 —— 用面向对象组织代码
开发语言·c++
hui函数7 小时前
Python系列Bug修复|如何解决 pip install -r requirements.txt 私有仓库认证失败 401 Unauthorized 问题
python·bug·pip
hui函数7 小时前
Python系列Bug修复|如何解决 pip install -r requirements.txt 子目录可编辑安装缺少 pyproject.toml 问题
python·bug·pip
向量引擎7 小时前
复刻“疯狂的鸽子”?用Python调用Sora2与Gemini-3-Pro实现全自动热点视频流水线(附源码解析)
开发语言·人工智能·python·gpt·ai·ai编程·api调用
郑泰科技7 小时前
快速地图匹配(FMM)的开源工具与代码示例
c++·windows·python·交通物流
CoderCodingNo7 小时前
【GESP】C++五级练习(贪心思想考点) luogu-P1115 最大子段和
开发语言·c++·算法
a程序小傲7 小时前
得物Java面试被问:边缘计算的数据同步和计算卸载
java·开发语言·数据库·后端·面试·golang·边缘计算
云和数据.ChenGuang7 小时前
fastapi flask django区别
人工智能·python·django·flask·fastapi