使用Python和OpenWeatherMap API查找任何城市的当前天气
在本教程中,我们将使用**OpenWeatherMap** API获取城市的实时天气。要使用OpenWeatherMap API,我们必须获取API密钥。我们将通过在他们的网站上创建一个帐户来获得它。
创建一个帐户并获取您的API密钥。每分钟最多可免费进行60次调用。如果您需要更多调用,则需要付费。对于本教程,免费版本就足够了。我们需要**requests**模块来进行HTTP请求,并需要**JSON**模块来处理响应。请按照以下步骤获取任何城市的实时天气。
导入requests和JSON模块。
初始化天气API的基本URL https://api.openweathermap.org/data/2.5/weather?。
初始化城市和API密钥。
使用API密钥和城市名称更新基本URL。
使用requests.get()方法发送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)
# checking the status code of the request
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
结论
如果您在学习本教程的过程中遇到任何困难,请在评论区留言。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP