python-3.x 无法在OpenWeatherMap API上输入状态或状态代码而不出现404错误

des4xlb0  于 2023-03-24  发布在  Python
关注(0)|答案(1)|浏览(141)

我试图从输入语句中同时输入城市和州或州代码,但每次我这样做,我都会得到404错误。我希望能够在输入语句中输入城市和州或州代码,(eidogg. Philadelphia,PA或纽约,NY)

import requests

API_KEY = "API KEY HERE"

city_state = input("Enter a city and state (e.g. Philadelphia, PA): ")
city, state_code = city_state.split(",")

url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{state_code}&appid={API_KEY}"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()

    city = data["name"]
    weather = data["weather"][0]["description"]
    feel_temp = data["main"]["feels_like"]
    temperature = data["main"]["temp"]
    humidity = data["main"]["humidity"]
    wind_speed = data["wind"]["speed"]

    farenheit = round((temperature - 273.15) * 1.8 + 32)
    feels_like = round((feel_temp - 273.15) * 1.8 + 32)
    mph = round((wind_speed * 2.237))

    print(f"City: {city}")
    print(f"Weather: {weather}")
    print(f"Feels Like: {feels_like}F")
    print(f"Temperature: {farenheit}F")
    print(f"Humidity: {humidity}%")
    print(f"Wind Speed: {mph}mph")
else:
    print(f"Error: {response.status_code}")
kgsdhlau

kgsdhlau1#

您应该在URL字符串中添加国家代码:

url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{state_code}, US&appid={API_KEY}"

https://openweathermap.org/api/geocoding-api
输出:

City: Philadelphia
Weather: clear sky
Feels Like: 49F
Temperature: 53F
Humidity: 33%
Wind Speed: 6mph

相关问题