代码示例
import requests
城市 = input("请输入城市名称: ")
api = "52d3168f9110d61fd582034ce6e48665"
网址 = f"https://api.openweathermap.org/data/2.5/weather?q={城市}&appid={api}&units=metric"
try:
天气资料 = requests.get(网址)
天气资料.raise_for_status() # 检查请求是否成功
数据 = 天气资料.json()
气温 = int(数据["main"]["temp"])
print(f"{城市}目前的气温是{气温}度")
except requests.exceptions.HTTPError as e:
if 天气资料.status_code == 401:
print("API密钥无效或无权限访问,请检查您的API密钥")
elif 天气资料.status_code == 404:
print("未找到指定城市,请检查城市名称")
else:
print(f"HTTP请求出错: {e}")
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
except KeyError:
print("无法从API响应中获取气温数据,请检查城市名称或稍后重试。")
