소프트웨어/python
네이버 주식 일별 시세 크롤링 (request을 이용, format json)
개발자_이훈규
2020. 2. 7. 09:30
요즘에 취미로 데이터 모으는 기법을 공부하고 있다.
특히 시계열 데이터를 다루는걸 하는데
pandas datareader로 읽어오면 일별 시세가 온전하지 않아서
naver 주식 일별 시세의 정보로 만드는 코드를 만들었다.
python 네이버 주식 일별 시세를
크롤링으로 pandas datareader형태로
시작일부터 종료일까지
json file로 export하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
import requests
import time
import pandas as pd
from bs4 import BeautifulSoup as bs
from datetime import datetime
def exportData(code, startdate, enddate):
isEnd = False
res = {
'index': [],
'data': []
}
print("Start")
page = 1
while isEnd != True:
url = "https://finance.naver.com/item/sise_day.nhn?code="+code+"&page="+ str(page)
response = requests.get(url)
html = bs(response.text, 'html.parser')
# parse
trList = html.find_all("tr", {"onmouseover":"mouseOver(this)"})
for tr in trList:
tdList = tr.find_all('td')
# print(tdList[0].text.strip()) # 날짜
# print(tdList[1].text.strip()) # 종가
# print(tdList[2].text.strip()) # 전일비
# print(tdList[3].text.strip()) # 시가
# print(tdList[4].text.strip()) # 고가
# print(tdList[5].text.strip()) # 저가
# print(tdList[6].text.strip()) # 거래량
date = tdList[0].text.strip() # 날짜
closePrice = int(tdList[1].text.strip().replace(',', '')) # 종가
diffPrice = int(tdList[2].text.strip().replace(',', '')) # 전일비
openPrice = int(tdList[3].text.strip().replace(',', '')) # 시가
highPrice = int(tdList[4].text.strip().replace(',', '')) # 고가
lowPrice = int(tdList[5].text.strip().replace(',', '')) # 저가
volume = int(tdList[6].text.strip().replace(',', '')) # 거래량
target = datetime.fromisoformat(date.replace('.', '-'))
if target < start:
isEnd = True
break
elif target < end and target > start:
print(target)
# insert index
res['index'].insert(0, date)
# insert data with ["High","Low","Open","Close","Volume","Adj Close"]
res['data'].insert(0, [highPrice, lowPrice, openPrice, closePrice, volume])
page += 1
time.sleep(2)
df = pd.DataFrame(data=res['data'], index=res['index'])
df.to_json(code+'.json', orient='split', date_format='index')
print("Start - Done")
code = "005930"
start = datetime(2019, 1, 1)
end = datetime(2019, 12, 31)
exportData(code, start, end)
|
cs |