⚙️ Data Handling
📌 KOBIS Open API 데이터 조작
import requests
import pandas as pd
base_url = "http://www.kobis.or.kr/kobisopenapi/webservice/rest/movie/searchMovieList.json"
my_parmas = {
"key": "API Key",
"itemPerPage": 40
}
res = requests.get(base_url, params=my_parmas)
if res.ok:
result = res.json()
else:
print("'Response Error!!!!")
directors_list = []
for data in result["movieListResult"]["movieList"]:
directors_list.append( data["directors"])
new_list = []
for idx, data in enumerate(result["movieListResult"]["movieList"]) :
one_data = data
if len(directors_list[idx]) != 0:
one_data = { **one_data, **directors_list[idx][0] }
new_list.append(one_data)
pd.DataFrame(new_list).drop(["directors","companys"], axis=1).fillna("")
📌 XML
- XML이란? : <태그> 값 </태그> 형식들로 이루어져있는 데이터 양식
- 파이썬의 XML 라이브러리
from bs4 import BeautifulSoup
- JSON 패키지와 BeautifulSoup 패키지의 차이
JSON |
BeautifulSoup |
파이썬의 정수 인덱스, 키 값 중심으로 값에 접근 |
find(태그), find_all(태그) 메서드를 중심으로 값에 접근 |
⚙️ Web Crawling
📌 Web Crawling
- Web Crawling 기법 : 내가 원하는 정보가 API로 제공되지 않고, 일반적인 웹사이트에 존재할 때 사용하는 기법
- Web Crawling 방법
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import time
date = "2023.12.18"
page = "1"
url = f"https://dart.fss.or.kr/dsac001/mainAll.do?selectDate={date}&sort=&series=&mdayCnt=0¤tPage={page}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
# soup.find("태그") or soup.find_all("태그")로 원하는 태그에 접근 가능
⚙️ 실습
📝 Web Crawling 실습
💡 사용할 데이터
date = "2023.12.18"
page = "1"
url = f"https://dart.fss.or.kr/dsac001/mainAll.do?selectDate={date}&sort=&series=&mdayCnt=0¤tPage={page}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
t = soup.find("tbody").find_all("tr")[0]
💡 1번 공시 제출 시간 출력
txt = t.find("td").text
re.sub(r"\r|\n|\t|\s", "", txt)
💡 1번 공시를 제출한 회사가 속한 시장 출력
t.find_all("td")[1].find_all("span")[1].get("title")
💡 1번 공시를 제출한 회사의 이름 출력
t.find_all("td")[1].find("a").text.strip()
💡 1번 공시를 제출한 회사의 코드값 출력
txt = t.find_all("td")[1].find_all("a")[0].get("href")
n = re.compile(r"'(\d+)'")
code = n.findall(txt)[0]
💡 1번 공시의 제목 출력
txt = t.find_all("td")[2].find_all("a")[0].get("title")
re.sub(r"\r|\n|\t", "", txt)
💡 1번 공시의 공시코드값 출력
txt = t.find_all("td")[2].find_all("a")[0].get("href")
n = re.compile(r"=(\d+)")
code = n.findall(txt)[0]
💡 1번 공시를 요청한 날짜 출력
t.find_all("td")[4].text
💡 100개 공시에 대한 정보 출력 및 출력한 내용을 데이터프레임으로 저장
data = []
for i in range(100):
t = soup.find("tbody").find_all("tr")[i]
temp = t.find("td").text
time = re.sub(r"\r|\n|\t|\s", "", temp)
market = t.find_all("td")[1].find_all("span")[1].get("title")
name = t.find_all("td")[1].find("a").text.strip()
temp = t.find_all("td")[1].find_all("a")[0].get("href")
n = re.compile(r"'(\d+)'")
code = n.findall(temp)[0]
temp = t.find_all("td")[2].find_all("a")[0].get("title")
title = re.sub(r"\r|\n|\t", "", temp)
temp = t.find_all("td")[2].find_all("a")[0].get("href")
n = re.compile(r"=(\d+)")
code_val = n.findall(temp)[0]
date = t.find_all("td")[4].text
data.append([time, market, name, code, title, code_val, date])
print(time, market, name, code, title, code_val, date)
print("----------------------------------------------------------------------------------------")
💡 1~4페이지에 걸쳐있는 모든 공시정보들을 하나의 데이터프레임에 담기
date = "2023.12.18"
data = []
for i in range(4):
url = f"https://dart.fss.or.kr/dsac001/mainAll.do?selectDate={date}&sort=&series=&mdayCnt=0¤tPage={str(i+1)}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
t = soup.find("tbody").find_all("tr")[0]
for i in range(len(soup.find("tbody").find_all("tr"))):
t = soup.find("tbody").find_all("tr")[i]
temp = t.find("td").text
time = re.sub(r"\r|\n|\t|\s", "", temp)
market = t.find_all("td")[1].find_all("span")[1].get("title")
name = t.find_all("td")[1].find("a").text.strip()
temp = t.find_all("td")[1].find_all("a")[0].get("href")
n = re.compile(r"'(\d+)'")
code = n.findall(temp)[0]
temp = t.find_all("td")[2].find_all("a")[0].get("title")
title = re.sub(r"\r|\n|\t", "", temp)
temp = t.find_all("td")[2].find_all("a")[0].get("href")
n = re.compile(r"=(\d+)")
code_val = n.findall(temp)[0]
date = t.find_all("td")[4].text
data.append([time, market, name, code, title, code_val, date])
pd.DataFrame(data, columns=["시간", "시장", "회사명", "회사코드", "제목", "공시코드", "공시날짜"])
💡 시작일자, 종료일자를 받아서 기간 동안의 모든 공시를 정리해 데이터프레임으로 출력하는 함수 만들기
from datetime import datetime, timedelta
def dfmaker(start_date, end_date):
data = []
pages = "1"
dates = []
start_date_str = start_date
start_date = datetime.strptime(start_date_str, '%Y.%m.%d')
end_date_str = end_date
end_date = datetime.strptime(end_date_str, '%Y.%m.%d')
current_date = start_date
while current_date <= end_date:
dates.append(current_date.strftime('%Y.%m.%d'))
current_date += timedelta(days=1)
for i in range(len(dates)):
url = f"https://dart.fss.or.kr/dsac001/mainAll.do?selectDate={dates[i]}&sort=&series=&mdayCnt=0¤tPage={pages}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
t = soup.find("tbody").find_all("tr")[0]
for i in range(len(soup.find("tbody").find_all("tr"))):
t = soup.find("tbody").find_all("tr")[i]
temp = t.find("td").text
time = re.sub(r"\r|\n|\t|\s", "", temp)
market = t.find_all("td")[1].find_all("span")[1].get("title")
name = t.find_all("td")[1].find("a").text.strip()
temp = t.find_all("td")[1].find_all("a")[0].get("href")
n = re.compile(r"'(\d+)'")
code = n.findall(temp)[0]
temp = t.find_all("td")[2].find_all("a")[0].get("title")
title = re.sub(r"\r|\n|\t", "", temp)
temp = t.find_all("td")[2].find_all("a")[0].get("href")
n = re.compile(r"=(\d+)")
code_val = n.findall(temp)[0]
date = t.find_all("td")[4].text
data.append([time, market, name, code, title, code_val, date])
return(pd.DataFrame(data, columns=["시간", "시장", "회사명", "회사코드", "제목", "공시코드", "공시날짜"]))