使用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
結論
如果您在學習本教程的過程中遇到任何困難,請在評論區留言。
廣告