You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取天气描述?Python调用OpenWeatherMap API无法输出描述问题

问题解决:OpenWeatherMap API天气描述提取错误

错误原因

OpenWeatherMap的weather接口返回数据中,weather字段是列表类型,而非直接的字典。你直接通过weather_data['weather']['description']取值会触发类型错误,因为列表不能用字符串作为索引。

修正方案

修改天气描述的提取代码,先通过索引[0]获取weather列表中的第一个元素(当前天气信息的字典),再提取description字段:

import requests

print('Input city')
city = input()

url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&lang=en&appid=79d1ca96933b0328e1c7e3e7a26cb347'

weather_data = requests.get(url).json()

# 先检查请求是否成功,避免城市不存在等报错
if weather_data.get('cod') == 200:
    temperature = round(weather_data['main']['temp'])
    temperature_feels = round(weather_data['main']['feels_like'])
    # 修正天气描述提取方式
    weather_description = weather_data['weather'][0]['description']

    print(f"The temperature in {city} is {temperature} °C")
    print(f'Feels like {temperature_feels} °C')
    print(f"Weather: {weather_description}")
else:
    print(f"Error: {weather_data.get('message', 'Unknown error')}")

关键说明

  • weather_data['weather']返回的是一个列表,里面包含了天气相关的条目(通常仅1条)
  • 使用[0]索引获取列表中的第一个元素(对应当前天气的详细字典)
  • 从该字典中提取description字段,即可得到正确的天气描述

内容的提问来源于stack exchange,提问作者lGus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:00:03