728x90
반응형
.
부동산 API를 이용해서 실거래가 데이터를 가저온 후 구글 스프레드 시트에 저장하는 법입다.
우선 API를 사용하기 위해서는 공공데이터 포털 > 국토교통부 실거래가 정보 > '아파트 매매 실거래 상세자료' 활용 신청을 해야 합니다.
https://www.data.go.kr/dataset/3050988/openapi.do
사이트에 들어가서 인증키를 받아야 합니다.
필요한 라이브러리 불러오기, API 요청 파라미터 설정
import os
import pandas as pd
import requests
from bs4 import BeautifulSoup
# API 요청 파라미터 설정
service_key = 'your-authentication-key-here'
year_month_day = '202002'
land_code = '11440'
num_rows = 1000
url = f'http://openapi.molit.go.kr/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTradeDev?LAWD_CD={land_code}&DEAL_YMD={year_month_day}&serviceKey={service_key}&numOfRows={num_rows}'
랜드코드는 아래 URL 참조
https://github.com/drtagkim/kor_gg_code/blob/master/region_code5.csv
엑셀 파일로 출력하기 위한 함수 설정
API에 요청해 데이터 파싱
엑셀 파일에 저장하기 위한 리스트 작성
# 엑셀 파일로 출력하기 위한 함수
def export_to_excel(item_list, file_name):
# 빈 데이터프레임 생성
df = pd.DataFrame(columns=item_list[0])
# 데이터프레임에 데이터 추가
for data in item_list:
df.loc[len(df)] = data
# 매매일 기준으로 내림차순 정렬
df = df.sort_values(by='매매일', ascending=False)
# 엑셀 파일로 저장
writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
df.to_excel(writer, sheet_name='마포구', index=False)
writer.save()
# 저장된 파일 열기
os.startfile(file_name)
# API 요청해서 데이터 파싱하기
res = requests.get(url)
soup = BeautifulSoup(res.content, 'lxml-xml')
items = soup.findAll('item')
# 엑셀 파일로 저장하기 위한 키 리스트
key_list = [
'거래금액',
'건축년도',
'년',
'도로명',
'도로명건물본번호코드',
'도로명건물부번호코드',
'도로명시군구코드',
'도로명일련번호코드',
'도로명코드',
'법정동',
'법정동본번코드',
'법정동부번코드',
'법정동시군구코드',
'법정동읍면동코드',
'법정동지번코드',
'아파트',
'월',
'일',
'전용면적',
'지번',
'지역코드',
'층',
]
파싱한 데이터 리스르로 저장한 후 엑셀파일로 저장
# 파싱한 데이터를 리스트로 저장
item_list = []
for v in items:
item = {}
for key in key_list:
item[key] = v.find(key).text
item['매매일'] = int(item['년']) * 10000 + int(item['월']) * 100 + int(item['일'])
item['거래금액'] = int(item['거래금액'].replace(',', ''))
item['전용면적'] = float(item['전용면적'])
item['층'] = int(item['층'])
item['건축년도'] = int(item['건축년도'])
item_list.append(item)
# 엑셀 파일로 저장
export_to_excel(item_list, 'c:\\abce.xlsx')
저장한 정보를 google sheet에 넣을 수도 있다.
google sheet api 값을 가져와합니다.
https://console.cloud.google.com/
from google.oauth2.service_account import Credentials
import gspread
# Replace with your own values
json_file_name = 'api 키 값이 들어 있는 json 파일'
spreadsheet_url = '시트 url'
spreadsheet_name = '구글 스프레드 시트 이름'
worksheet_name = '시트 이름'
# Use your Google Sheets API credentials to authenticate
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = Credentials.from_service_account_file(json_file_name, scopes=scope)
# Get the worksheet
client = gspread.authorize(creds)
worksheet = client.open_by_url(spreadsheet_url).worksheet(worksheet_name)
# Insert the rows with the parsed news data
worksheet.insert_rows([itemList.columns.values.tolist()] + itemList.values.tolist())
반응형