我试图从输入语句中输入城市和州或州代码,但每次这样做都会收到 404 错误。我希望能够在输入语句中输入城市和州或州代码(例如宾夕法尼亚州费城或纽约州纽约)
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}")
您应该将国家/地区代码添加到网址字符串中:
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