在本教程中,我们将使用OpenWeatherMap API获取城市的天气。要使用OpenWeatherMap API,我们必须获取API密钥。我们将通过在他们的网站上创建一个帐户来获得它。
创建一个帐户并获取您的API密钥。免费,直到每分钟60个电话为止。如果您想要更多,则必须付费。对于本教程,免费版本就足够了。我们需要HTTP请求的请求模块和JSON模块来处理响应。请按照以下步骤操作任何城市的天气。
导入请求和JSON模块。
初始化天气API的基本URL https://api.openweathermap.org/data/2.5/weather?。
初始化城市和API密钥。
使用API密钥和城市名称更新基本URL。
使用request.get()方法发送获取请求。
然后从响应中使用JSON模块提取天气信息。
让我们看一下代码。
# importing requests and json import requests, json # base URL BASE_URL = "https://api.openweathermap.org/data/2.5/weather?" # City Name CITY = "Hyderabad" # API key API_KEY = "Your API Key" # upadting the URL URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY # HTTP request response = requests.get(URL) #检查请求的状态代码 if response.status_code == 200: #以json格式获取数据 data = response.json() #获取主 dict 块 main = data['main'] #获取温度 temperature = main['temp'] #获取湿度 humidity = main['humidity'] #获得气压 pressure = main['pressure'] #天气报告 report = data['weather'] print(f"{CITY:-^30}") print(f"Temperature: {temperature}") print(f"Humidity: {humidity}") print(f"Pressure: {pressure}") print(f"Weather Report: {report[0]['description']}") else: #显示错误消息 print("Error in the HTTP request")
输出结果
如果运行上面的程序,您将得到以下结果。
----------Hyderabad----------- Temperature: 295.39 Humidity: 83 Pressure: 1019 Weather Report: mist
如果您在遵循本教程方面遇到任何困难,请在评论部分中提及它们。