【问题标题】:Not showing measures in results when using Weatherbit API使用 Wea​​therbit API 时未在结果中显示度量
【发布时间】:2021-12-08 21:54:32
【问题描述】:

使用Python,需要使用网站APIhttps://www.weatherbit.io/api显示当前天气数据。天气数据应以文本形式显示。我得到了类似的东西,但它没有按预期工作,因此它显示以下没有措施:

#Output

 Enter city name : Paris
 Temperature (in kelvin unit) = ['temp']
 atmospheric pressure (in hPa unit) = ['pres']
 humidity (in percentage) = ['rh']
 description = ['description']

完整代码:

# import required modules
import requests, json

# Enter your API key here
api_key = "API_key"

# base_url variable to store url
base_url = "https://api.weatherbit.io/v2.0/current?"
# Give city name
city_name = input("Enter city name : ")

# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# get method of requests module
# return response object
response = requests.get(complete_url)

# json method of response object
# convert json format data into
# python format data
x = response.json()


# store the value corresponding
# to the "temp" key of y
current_temperature = ["temp"]

# store the value corresponding
# to the "pressure" key of y
current_pressure = ["pres"]

# store the value corresponding
# to the "humidity" key of y
current_humidity = ["rh"]

# store the value of "weather"
# key in variable z
z = ["weather"]

# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = ["description"]

# print following values
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 - 它必须是x["temp"],但您只有["temp"]

标签: python api weather-api


【解决方案1】:

您在所有行中都忘记了x

为了使其更具可读性,我将使用名称 data 而不是无矿 x

data = response.json()

current_temperature = data["temp"]
current_pressure    = data["pres"]
current_humidity    = data["rh"]
z                   = data["weather"]
weather_description = data["description"]

顺便说一句:

您可以使用名称 weather 而不是 z 以使代码更具可读性。

查看更多PEP 8 -- Style Guide for Python Code


编辑:

包含其他更改的完整代码(但我没有 API_KEY 来测试它)。

  • 你不需要import json
  • 出于安全考虑,您可以从环境(或 dot file)中读取 API_KEY
  • 您不必创建完整的 URL,但您可以为此使用 get(..., params=...)
  • 您可以使用f-string 使代码更具可读性
  • 如果您对每一行分别使用print(),代码的可读性会更高。
import requests

#import os
#api_key = os.getenv("API_KEY")

api_key = "API_KEY"

city_name = input("Enter city name : ")

url = "https://api.weatherbit.io/v2.0/current" # url without `?`

payload = {
    'appid': api_key,
    'q': city_name,
}   

response = requests.get(url, params=payload)

data = response.json()

if 'error' in data:
    print('Error:', data['error'])
else:
    temperature = data["temp"]
    pressure    = data["pres"]
    humidity    = data["rh"]
    weather     = data["weather"]
    description = data["description"]

    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")
    print(f"humidity (in percentage) = {humidity}")
    print(f"description = {description}")

编辑:

我检查了current weather 的 API 文档,它在 URL 中使用了不同的名称。

应该是的

payload = {
    'key': api_key,
    'city': city_name,
    #'lang': 'pl'  # for descriptions in my native language Polish
}   

它在data["data"][0]["temp"] 中提供temperature,在data["data"][0]["pres"] 中提供pressure 等 - 所以它需要

temperature = data["data"][0]["temp"]
pressure    = data["data"][0]["pres"]
# etc.

或者你可以这样做

data = data['data'][0]

temperature = data["temp"]
pressure    = data["pres"]

它还在data["data"][0]["weather"]["description"]中给出description

在其他请求中,结果可能比[0] 更多,因此您可能需要使用for-loop

data = data['data']

for item in data:
    temperature = item["temp"]
    pressure    = item["pres"]
    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")

import requests

#import os
#api_key = os.getenv("API_KEY")

api_key = "ef.............................."

#city_name = input("Enter city name : ")

city_name = 'Warsaw'
url = "https://api.weatherbit.io/v2.0/current" # url without `?`

payload = {
    'key': api_key,
    'city': city_name,
    #'lang': 'pl'  # for descriptions in my native language Polish
}   

response = requests.get(url, params=payload)

data = response.json()

if 'error' in data:
    print('Error:', data['error'])
else:
    #print(data)
    
    data = data['data'][0]
    
    temperature = data["temp"]
    pressure    = data["pres"]
    humidity    = data["rh"]
    weather     = data["weather"]
    description = data["weather"]["description"]
    
    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")
    print(f"humidity (in percentage) = {humidity}")
    print(f"description = {description}")

【讨论】:

  • 非常感谢您的详细解释。一件事我尝试了您建议的改进方式,但出现错误Error: API key is required. 但我输入了 api 密钥
  • 我检查了Current weather 的文档,它需要key= 而不是appid=city= 而不是q=。当我使用我的 API 运行它时,它会获取数据,但格式不同 - 它需要获取 data["data"][0]["temp"] 来获取温度 - 并且类似于其他值 - 所以我似乎你的代码完全错误。
  • 我添加了包含所有更改的代码,它对我有用。
  • 非常感谢您的详尽解释和您的大力帮助,现在我也检查了一下,效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 2017-05-28
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多