Python38行代码实现全球天气实时查询(用拼音)温湿度和风速

import requests
import json

def get_weather(city):
    api_key = "003970a6825771f12dd5fe353479ff92"  # 替换为你自己的API Key
    base_url = "http://api.openweathermap.org/data/2.5/weather"

    # 构建请求参数
    params = {
        "q": city,              # 城市名
        "appid": api_key,       # API Key
        "units": "metric"       # 温度单位为摄氏度
    }

    # 发送GET请求获取天气数据
    response = requests.get(base_url, params=params)
    data = json.loads(response.text)

    # 解析返回的JSON数据
    if data["cod"] == 200:
        weather = data["weather"][0]["main"]           # 天气情况
        description = data["weather"][0]["description"] # 天气描述
        temperature = data["main"]["temp"]              # 温度
        humidity = data["main"]["humidity"]             # 湿度
        wind_speed = data["wind"]["speed"]              # 风速

        # 输出天气信息
        print(f"Weather in {city}:")
        print(f" - Weather: {weather} ({description})")
        print(f" - Temperature: {temperature}°C")
        print(f" - Humidity: {humidity}%")
        print(f" - Wind Speed: {wind_speed} m/s")
    else:
        print("Failed to fetch weather data.")

# 测试
city_name = input("请输入城市名:")
get_weather(city_name)

https://home.openweathermap.org/申请账号后,将自己的API_KEY输入即可

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值