๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Python/Data Visualization

[API ๋‹ค๋ฃจ๊ธฐ] XML > JSON > dataframe ๋ณ€ํ™˜ํ•˜๊ธฐ

by ISLA! 2023. 8. 7.

๐Ÿ‘พ ๊ณต๊ณต๋ฐ์ดํ„ฐ ํฌํ„ธ์˜ ๋ถ€๋™์‚ฐ ์‹ค๊ฑฐ๋ž˜๊ฐ€ ์ž๋ฃŒ๋ฅผ ๊ฐ€์ ธ์™€๋ณด์ž.

  • requests, pandas ๋‘ ๊ฐœ์˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ import
  • ์ธ์ฆํ‚ค์™€ ํŽ˜์ด์ง€๋ฒˆํ˜ธ, ํŽ˜์ด์ง€๋‹น ๊ฒฐ๊ณผ์ˆ˜, ์ง€์—ญ์ฝ”๋“œ, ๊ณ„์•ฝ ์›”์€ format ๋ฌธ์ž์—ด๋กœ ์ฒ˜๋ฆฌํ•˜์—ฌ ์œ ๋™์ ์œผ๋กœ ์„ ํƒํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค.
  • url ๊ธฐ๋ณธํ˜•์„ ๋ฌธ์ž์—ด๋กœ ์ž…๋ ฅํ•˜๊ณ , ์œ„์˜ ํ•ญ๋ชฉ๋“ค์„ { } ์•ˆ์— ๋„ฃ์–ด ํฌ๋งทํŒ…ํ•œ๋‹ค.
  • req ์— url๋กœ๋ถ€ํ„ฐ xml ๋ฐ์ดํ„ฐ ์š”์ฒญํ•˜๊ณ , req.text๋กœ ์ด๋ฅผ ํ™•์ธํ•œ๋‹ค.
import requests
import pandas as pd 

serviceKey = "์ธ์ฆํ‚ค"
pageNo = 1 # ํŽ˜์ด์ง€ ๋ฒˆํ˜ธ
numOfRows = 1000 # ํ•œ ํŽ˜์ด์ง€ ๊ฒฐ๊ณผ์ˆ˜
LAWD_CD = 11560 # ์ง€์—ญ์ฝ”๋“œ
DEAL_YMD = 202307 # ๊ณ„์•ฝ์›”
url = f'http://openapi.molit.go.kr/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTradeDev?serviceKey={serviceKey}&pageNo={pageNo}&numOfRows=10&LAWD_CD={LAWD_CD}&DEAL_YMD={DEAL_YMD}'
req = requests.get(url)
req.text

๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค

 

XML -> JSON ์œผ๋กœ

์ข€ ๋” ๋ณด๊ธฐ ์‰ฝ๊ฒŒ ์ด๋ฅผ ๊ฐ€๊ณตํ•˜๊ธฐ ์œ„ํ•ด json ํ˜•์‹์œผ๋กœ ๋งŒ๋“ ๋‹ค์Œ, pandas dataframe์œผ๋กœ ๋งŒ๋“ค๊ฒƒ์ด๋‹ค.

๋จผ์ €, json์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๋‹ค์Œ์„ ์ž‘์„ฑํ•œ๋‹ค.

  • xmltodict ๋ผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์„ค์น˜ํ•œ ๋‹ค์Œ
  • xmldict๋ฅผ Import
!pip install xmltodict
import xmltodict
  • xmldict๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์•ž์„œ ๋ฐ›์•„์˜จ req.text๋ผ๋Š” XML ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒ์‹ฑํ•œ๋‹ค >> data_dict ์— ์ €์žฅ
data_dict = xmltodict.parse(req.text)
data_dict

์ด๋ ‡๊ฒŒ json ํ˜•์‹์œผ๋กœ ์นœ๊ทผํ•œ(?) ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๊ฐ€ ๋‚˜ํƒ€๋‚œ๋‹ค.

 

JSON -> DataFrame ์œผ๋กœ

  • ๋งˆ์ง€๋ง‰์œผ๋กœ json๋ฐ์ดํ„ฐ๋ฅผ dataframe์œผ๋กœ ๋ฐ”๊พธ์–ด๋ณด์ž.
  • ์œ„์˜ ๊ฒฐ๊ณผ๊ฐ’์—์„œ ๊ตฌ์ฒด์ ์œผ๋กœ ํ™•์ธํ•˜๊ณ  ์‹ถ์€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋”•์…”๋„ˆ๋ฆฌ์˜ ๊ตฌ์กฐ๋ฅผ ๋”ฐ๋ผ ์›ํ•˜๋Š” ํ‚ค ๊ฐ’์„ ์„ค์ •ํ•œ๋‹ค
pd.DataFrame(data_dict['response']['body']['items']['item'])

โญ‘ ์ด๋ ‡๊ฒŒ ํ‘œ ๋ชจ์–‘์œผ๋กœ ๊น”๋”ํ•œ ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„์ด ๋‚˜ํƒ€๋‚˜๋ฉด ์™„์„ฑ์ด๋‹ค

728x90