Python/크롤링
api 크롤링 다중데이터 수집
GinaKim
2024. 2. 1. 20:47
728x90
서울열린데이터 광장에서 api 크롤링을 할 때, 한번에 1천건의 데이터만 불러올 수 있다.
많은 데이터가 필요하면 반복문을 써서 데이터를 수집해야 한다.
http://openapi.seoul.go.kr:8088/(인증키)/xml/tbLnOpendataRtmsV/1/5/
위 URL에서 /1/5 부분이 데이터 수를 결정하는하는 것이기 때문에 해당 위치의 숫자만 바꿔주면 된다.
http://openapi.seoul.go.kr:8088/(인증키)/json/tbLnOpendataRtmsV/1/1000/
http://openapi.seoul.go.kr:8088/(인증키)/json/tbLnOpendataRtmsV/1001/2000/
.
.
.
1. 우선 해당 URL을 생성하기 위해 반복문을 만든다.
for i in range(1, 5):
URL = f'http://openapi.seoul.go.kr:8088/{SERVICE_KEY}/json/tbLnOpendataRtmsV/{1 + (i-1) * 1000}/{i *1000}/'
print(URL)
이렇게 하면
2. 이제 원하는 부분의 데이터를 수집하고 수집한 데이터들을 한 데이터프레임에 합친다.
import requests
import json
import pandas as pd
df = None
for i in range(1, 5):
URL = f'http://openapi.seoul.go.kr:8088/{SERVICE_KEY}/json/tbLnOpendataRtmsV/{1 + (i-1) * 1000}/{i *1000}/'
req = requests.get(URL)
content = req.json() #응답받은 JSON데이터를 파싱
result = pd.DataFrame(content['tbLnOpendataRtmsV']['row'])
df = pd.concat([df, result])
df = df.reset_index(drop=True)
df
총 4,000개의 데이터가 수집됐다!
해당 데이터 csv로 저장하려면 아래 코드로 저장하면 된다.
df.to_csv('저장할 파일 이름.csv', index=False)
728x90