이 튜토리얼에서는 OpenWeatherMap 을 사용하여 도시의 날씨를 얻을 것입니다. API. OpenWeatherMap API를 사용하려면 API 키를 가져와야 합니다. 웹사이트에서 계정을 생성하면 받을 수 있습니다.
계정을 만들고 API 키를 받으세요. 분당 60회까지는 무료입니다. 그 이상을 원하면 지불해야 합니다. 이 튜토리얼에서는 무료 버전으로 충분합니다. 요청이 필요합니다. HTTP 요청 및 JSON용 모듈 응답과 함께 작동하는 모듈. 도시의 날씨에 따라 아래 단계를 따르세요.
-
요청 및 JSON 모듈을 가져옵니다.
-
날씨 API https://api.openweathermap.org/data/2.5/weather?의 기본 URL을 초기화합니다.
-
도시 및 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
결론
튜토리얼을 따라가는 데 어려움이 있으면 댓글 섹션에 언급하세요.