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")
相关推荐
毕设源码-邱学长2 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
rookieﻬ°3 小时前
PHP框架漏洞
开发语言·php
猿界零零七4 小时前
pip install mxnet 报错解决方案
python·pip·mxnet
炸膛坦客4 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
兑生4 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
炸膛坦客5 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲5 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
不只会拍照的程序猿6 小时前
《嵌入式AI筑基笔记02:Python数据类型01,从C的“硬核”到Python的“包容”》
人工智能·笔记·python
Jay_Franklin6 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法