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

使用Weatherbit API调用天气数据结果未显示具体数值如何解决

问题原因
  • API请求参数不符合Weatherbit要求:该平台的接口密钥参数为key,你代码里误用了其他天气接口的appid参数,会导致鉴权失败。
  • 没有正确从接口返回的JSON数据中提取字段:你代码中类似current_temperature = ["temp"]的写法是直接创建了包含字符串的列表,并未实际读取接口返回的结构化数据。Weatherbit的当前天气接口返回结果中,真实数据存储在data数组的第0位元素里,需要从该对象中读取对应字段。
修正后完整代码
# 导入所需模块
import requests

# 填入你在Weatherbit申请的有效API密钥
api_key = "你的真实API_key"

# 接口基础地址
base_url = "https://api.weatherbit.io/v2.0/current?"
# 接收用户输入的城市名
city_name = input("Enter city name : ")

# 拼接完整请求地址,注意密钥参数为key,城市参数为city
complete_url = base_url + "key=" + api_key + "&city=" + city_name

# 发送请求
response = requests.get(complete_url)
# 解析返回的JSON数据
x = response.json()

# 提取当前天气数据主体
weather_data = x['data'][0]

# 读取对应字段值
current_temperature = weather_data["temp"]
current_pressure = weather_data["pres"]
current_humidity = weather_data["rh"]
weather_description = weather_data["weather"]["description"]

# 输出结果
print(" Temperature (in kelvin unit) = " +
      str(current_temperature) +
      "\n atmospheric pressure (in hPa unit) = " +
      str(current_pressure) +
      "\n humidity (in percentage) = " +
      str(current_humidity) +
      "\n description = " +
      str(weather_description))
注意事项

如果运行报错,可以先打印x变量查看接口返回的错误提示,排查密钥有效性、城市名格式等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:24:01