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
    评论
要使用Python实时获取天气温湿度,你需要先获取对应城市的天气预报数据。以下是一种获取天气预报数据的方法: ```python import requests # 获取城市天气预报 def get_weather(city): # 构造请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 构造请求链接 url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city # 发送请求 res = requests.get(url, headers=headers) # 解析返回的JSON数据 data = res.json() return data ``` 上述代码中,我们使用requests库向一个天气预报API发送请求,然后解析返回的JSON数据,获取对应城市的天气预报数据。 接下来,要获取实时天气温湿度,需要从获取天气预报数据中提取出温湿度信息。以下是一种提取温湿度信息的方法: ```python # 获取实时天气温湿度 def get_realtime_weather(city): # 获取天气预报数据 data = get_weather(city) # 提取实时温湿度信息 realtime_weather = {} realtime_weather['温度'] = data['data']['wendu'] + '℃' realtime_weather['湿度'] = data['data']['shidu'] return realtime_weather ``` 上述代码中,我们首先调用`get_weather`函数获取对应城市的天气预报数据,然后从数据中提取出温度和湿度信息,存储到一个字典中返回。 最后,你可以在程序中调用`get_realtime_weather`函数获取实时天气温湿度信息。例如: ```python city = '北京' realtime_weather = get_realtime_weather(city) print('城市:', city) print('温度:', realtime_weather['温度']) print('湿度:', realtime_weather['湿度']) ``` 希望这些代码能帮到你!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值