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")
相关推荐
花酒锄作田4 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪8 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽8 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战9 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋15 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
BingoGo17 小时前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack17 小时前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python