使用 Python 中的 OpenWeatherMap API 查找任何城市的当前天气
pythonserver side programmingprogramming
在本教程中,我们将使用 OpenWeatherMap API 获取城市的天气。要使用 OpenWeatherMap API,我们必须获取 API 密钥。我们将通过在其网站上创建一个帐户来获取它。
创建一个帐户并获取您的 API 密钥。每分钟 60 次调用之前是免费的。如果您想要更多,则必须付费。对于本教程,免费版本就足够了。我们需要 requests 模块来处理 HTTP 请求,以及 JSON 模块来处理响应。按照以下步骤获取任意城市的天气信息。
导入请求和 JSON 模块。
初始化天气 API 的基本 URL https://api.openweathermap.org/data/2.5/weather?。
初始化城市和 API 密钥。
使用 API 密钥和城市名称更新基本 URL。
使用 request.get() 方法发送获取请求。
并使用 JSON 模块从响应中提取天气信息。
示例
让我们看看代码。
# 导入请求和 json import requests, json # 基本 URL BASE_URL = "https://api.openweathermap.org/data/2.5/weather?" # 城市名称 CITY = "海得拉巴" # API 密钥 API_KEY = "您的 API 密钥" # 更新 URL URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY # HTTP 请求 response = request.get(URL) # 检查请求的状态代码 if response.status_code == 200: # getting data in the json format data = response.json() # getting the main dict block main = data['main'] # getting temperature temperature = main['temp'] # getting the humidity humidity = main['humidity'] # getting the pressure pressure = main['pressure'] # weather report 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: # showing the error message print("Error in the HTTP request")
输出
如果你运行上述程序,你将得到以下结果。
----------Hyderabad----------- Temperature: 295.39 Humidity: 83 Pressure: 1019 Weather Report: mist
结论
如果您在学习本教程时遇到任何困难,请在评论部分中提及。