공공 Data 활용을 위한 service_key 신청은
Link를 참조.
| |
| import datetime as dt |
| import requests as req |
| from bs4 import BeautifulSoup |
| |
| w_items = {"POP":["강수확률", "%"], "PTY":["강수형태", ""], "R06":["6시간 강수량", "mm"], "REH":["습도", "%"], "S06":["6시간 신적설", "cm"], |
| "SKY":["하늘상태", ""], "T3H":["3시간 기온", "°C"], "TMN":["아침 최저 기온", "°C"], "TMX":["낮 최고 기온", "°C"], |
| "UUU":["풍속(동서성분)","m/s"], "VVV":["풍속(남북성분)","m/s"], "WAV":["파고", "m"], "VEC":["풍향", ""], "WSD":["풍속", "m/s"]} |
| wind_dict = {0:"N",1:"NNE",2:"NE",3:"ENE",4:"E",5:"ESE",6:"SE",7:"SSE",8:"S",9:"SSW",10:"SW",11:"WSW",12:"W",13:"WNW",14:"NW",15:"NNW",16:"N"} |
| rain_dict = {0:"없음", 1:"비", 2:"진눈깨비", 3:"눈"} |
| |
| |
| def get_rpt_time(): |
| base_time = dt.datetime.now() - dt.timedelta(hours=2) - dt.timedelta(minutes=10) |
| hour = int(base_time.strftime("%H")) |
| rehour = str(hour//3*3 + 2).zfill(2) |
| return [base_time.strftime("%Y%m%d"), rehour + "00"] |
| |
| |
| def get_wind_type(i): |
| return wind_dict[(i + 22.5 * 0.5)//22.5] |
| |
| def get_sky_status(i): |
| if i >= 0 and i <= 2: return "맑음" |
| elif i >= 3 and i <= 5: return "구름조금" |
| elif i >= 6 and i <= 8: return "구름많음" |
| elif i >= 9 and i <= 10: return "흐림" |
| |
| def get_real_value(c, s): |
| if c.string == "VEC": |
| return get_wind_type(int(s.string)) |
| elif c.string == "SKY": |
| return get_sky_status(int(s.string)) |
| elif c.string == "PTY": |
| return rain_dict[int(s.string)] |
| return s.string |
| |
| |
| service_key = "MJqwsP2VlmHlaRh0BMwMAtDvhfFu6k59h%2B1Svp2A%......." |
| nx = 60 |
| ny = 127 |
| |
| date = get_rpt_time() |
| |
| base_url = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastSpaceData?ServiceKey={}&base_date={}&base_time={}&nx={}&ny={}" |
| url = base_url.format(service_key, date[0], date[1], nx, ny) |
| |
| contents = req.get(url) |
| weather = BeautifulSoup(contents.content, 'lxml-xml') |
| |
| print("\t **************************************") |
| print("\t Report Time :", date[0], date[1]) |
| print("\t **************************************") |
| for item in weather.find_all("item"): |
| print("\t", w_items[item.category.string][0], " : ", get_real_value(item.category, item.fcstValue), end = "") |
| if w_items[item.category.string][1] != "": |
| print(w_items[item.category.string][1]) |
| else: |
| print() |
<결과>
**************************************
Report Time : 20180715 1100
**************************************
강수확률 : 10%
강수형태 : 없음
습도 : 50%
하늘상태 : 맑음
3시간 기온 : 31°C
낮 최고 기온 : 33.0°C
풍속(동서성분) : 3.1m/s
풍향 : WSW
풍속(남북성분) : 1.3m/s
풍속 : 3.4m/s
안녕하세요 질문드릴게 있어 댓글남깁니다. 혹시 최고 최저기온은 왜 출력이 안되는건지 알 수 있을까요?
답글삭제