Python/Crawling

[Python - Crawling] API 활용하여 날씨 예보 데이터 호출하기(OpenWeatherMap)

슈퍼짱짱 2023. 6. 29. 14:13
반응형

OpenWeatherMap API로 현재 날씨 / 예보 정보 호출하기

 

 

활용할 사이트는 다음과 같다.

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 


위 사이트에 들어가서 회원가입 or 로그인을 해주면 API는 자동으로 발급된다.

(이메일 인증 필수)

 

오른쪽 상단에 내 이름 클릭 -> My API keys 클릭

 

단, 발급 하자마자는 API가 작동하지 않는다. 어느정도 시간이 지나야 사용할 수 있게되는데, 본인은 2시간 정도 걸렸다.

(검색해보니 사람마다 걸리는 시간이 조금씩 다른 것 같기는하나, 대체로 2시간 이내에는 되는 듯 하다.)

 


Pricing을 누르면 어디까지 무료인지, 얼마에 어떤 서비스를 사용할 수 있는지 확인할 수 있다.

 

 

현재날씨와 3시간 단위 앞으로 5일 예보는 무료로 사용 가능하지만 

1시간 단위 예보나, 하루 단위 예보 등은 무료로 사용 불가하다.

 

또한, 무료일지라도 1분에 60번까지만 호출 가능하고, 한 달에 1,000,000까지 호출 가능하다.

 

 

각 API를 어떻게 호출하는지, 어떤 결과를 주는지 등등에 대한 설명은 API 메뉴에 자세히 설명되어있다.

 


무료로 호출이 가능한 API 중 3-hour Forecast 5 days를 파이썬으로 실습해보겠다.

 

 

 

먼저 필요한 라이브러리들을 불러와준다.

 

import requests
import json
import pandas as pd

 

호출할 API 주소는 다음과 같다.

 

 

원하는 지역의 위도와 경도를 파라미터로 전달해주어야 한다. 지역별 위도와 경도 역시도 API로 호출할 수 있는데,

예로 "울산" 지역의 위도와 경도는 다음과 같이 불러올 수 있다.

 

(아래 key에는 본인의 인증키를 입력해주면 된다.)

city = "Ulsan"
api = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=5&appid={key}"

location = requests.get(api)
location = json.loads(location.text)

 


 

이제 날씨 예보 API를 호출한다.

 

lat과 lon에 위에서 찾은 위도, 경도를 입력하고

key에는 본인 인증키를 입력한다.

 

units=metric도 추가로 입력해주었는데, 온도 단위를 섭씨로 받기 위함이다.

units에 아무 파라미터도 넣어주지 않으면 기본으로 화씨 온도가 return된다.

 

api = f"http://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&units=metric&appid={key}"

result = requests.get(api)
result = json.loads(result.text)

결과 발췌

 

각각이 의미하는게 뭔지는 역시 사이트에 상세히 나와있다.

 

사이트 발췌

 

 

2023-06-29 13:34:00에 호출했으며,

2023-06-29 06:00:00부터 2023-07-04 03:00:00까지 3시간 단위로 총 40개의 Timestamp가 return되었다.

 

 

맨 처음 2023-06-29 06:00:00 에 대해 결과 몇개만 파싱해보면 다음과 같다.

 

temp = result.copy()

i = 0
print("Timestamp : ",temp['list'][i]['dt_txt'],"\n")
print("온도 : ",temp['list'][i]['main']['temp'])
print("최저 기온 : ",temp['list'][i]['main']['temp_min'])
print("최고 기온 : ",temp['list'][i]['main']['temp_max'])
print("습도 : ",temp['list'][i]['main']['humidity'],"\n")

print("날씨 : ",temp['list'][i]['weather'][0]['main']) # Rain, Snow, etc.
print("강수량 : ", temp['list'][i]['rain']['3h'] if temp['list'][i]['weather'][0]['main'] == "rain" else 0)

 

 

40건 전체 중 온도, 습도, 강수량만 DataFrame으로 정리하면 다음과 같다.

 

weather = list()
for i in range(temp['cnt']) :
    ith = [temp['list'][i]['dt_txt'],
        temp['list'][i]['main']['temp'],
        temp['list'][i]['main']['temp_min'],
        temp['list'][i]['main']['temp_max'],
        temp['list'][i]['main']['humidity'],
        temp['list'][i]['rain']['3h'] if temp['list'][i]['weather'][0]['main'] == "Rain" else 0]
    weather.append(ith)

 

반응형