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")
相关推荐
小宇的天下几秒前
Cadence allegro---assign net
服务器·php·apache
JaguarJack2 分钟前
PHP 现在可以零成本构建原生 iOS 和 Android 应用 NativePHP for Mobile v3 发布
后端·php·laravel·服务端
m0_748233174 分钟前
Laravel+Vue:全栈开发终极指南
vue.js·php·laravel
雨季6664 分钟前
Flutter 三端应用实战:OpenHarmony “呼吸灯”——在焦虑时代守护每一次呼吸的数字禅修
开发语言·前端·flutter·ui·交互
开源技术1 小时前
深入了解Turso,这个“用Rust重写的SQLite”
人工智能·python
初恋叫萱萱1 小时前
构建高性能生成式AI应用:基于Rust Axum与蓝耘DeepSeek-V3.2大模型服务的全栈开发实战
开发语言·人工智能·rust
cyforkk2 小时前
12、Java 基础硬核复习:集合框架(数据容器)的核心逻辑与面试考点
java·开发语言·面试
u0109272712 小时前
RESTful API设计最佳实践(Python版)
jvm·数据库·python
我材不敲代码6 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
身如柳絮随风扬7 小时前
Java中的CAS机制详解
java·开发语言