2018~2019/Python

파이썬으로 미세먼지 정보 얻어오기

전기도둑 2018. 10. 26. 12:06

파이썬으로 미세먼지 정보 얻어오기



1. 공공데이터 포털에서 API KEY 발급받기

- https://www.data.go.kr/dataset/15000581/openapi.do


2. 소스코드

from urllib.request import Request, urlopen

from urllib.parse import urlencode, quote_plus,unquote

import xml.etree.ElementTree as ET


def dust(data):


    if 0 < int(data) <= 30:

        print('좋음')

    elif 30 < int(data) < 80:

        print('보통')

    elif 80 < int(data) <= 150:

        print('나쁨')

    elif 150 < int(data):

        print('매우나쁨')


API_key = unquote('공공데이터 포털에서 받은 API_KEY')

url = 'http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureLIst'

queryParams = '?' + urlencode({ quote_plus('ServiceKey') : API_key, quote_plus('numOfRows') : '10', quote_plus('pageNo') : '1', quote_plus('itemCode') : 'PM10', quote_plus('dataGubun') : 'HOUR', quote_plus('searchCondition') : 'MONTH' })


// Get 메소드를 통해 xml 가져오기

request = Request(url + queryParams)

request.get_method = lambda: 'GET'

response_body = urlopen(request).read().decode('utf-8')

root = ET.fromstring(response_body)


// 특정 시,도 정보 파싱하기

seoul = root.find('body').find('items').find('item').find('seoul')

gyeonggi = root.find('body').find('items').find('item').find('gyeonggi')


// 가져온 미세먼지 농도에 따라 결과 출력

dust(seoul.text)

dust(gyeonggi.text)