我试图从输入语句中同时输入城市和州或州代码,但每次我这样做,我都会得到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}")
1条答案
按热度按时间kgsdhlau1#
您应该在URL字符串中添加国家代码:
https://openweathermap.org/api/geocoding-api
输出: