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")
相关推荐
zhangjw342 小时前
Java基础语法:变量、数据类型与运算符,从原理到实战
java·开发语言
yaoxin5211236 小时前
384. Java IO API - Java 文件复制工具:Copy 示例完整解析
java·开发语言·python
Greyson16 小时前
Layui表格如何使用第三方插件实现树形展示.txt
jvm·数据库·python
2401_871696526 小时前
mysql行级锁失效的原因排查_检查查询条件与执行计划
jvm·数据库·python
NotFound4866 小时前
实战指南如何实现Java Web 拦截机制:Filter 与 Interceptor 深度分享
java·开发语言·前端
xzal126 小时前
python中,turtle基础知识笔记1
笔记·python·turtle
a9511416427 小时前
CSS如何实现元素隐藏不占位_使用display-none完全移除
jvm·数据库·python
Ava的硅谷新视界7 小时前
用了一天 Claude Opus 4.7,聊几点真实感受
开发语言·后端·编程
rabbit_pro7 小时前
Python调用onnx模型
开发语言·python