import requests
from bs4 import BeautifulSoup
from utils import *
class Naver():
def __init__(self):
super().__init__()
def get_bs_obj(self, url):
result = requests.get(url, headers=headers())
bs_obj = BeautifulSoup(result.content.decode('euc-kr', 'replace'),
"html.parser") # html.parser 로 파이썬에서 쓸 수 있는 형태로 변환
return bs_obj
def print_stock_price(self, code, page_num):
result = [[], [], [], [], [], [], [], [], []]
url = 'https://finance.naver.com/item/sise_day.nhn?code=' + code + '&page=' + str(page_num)
soup = self.get_bs_obj(url)
tr = soup.select('table > tr')
for i in range(1, len(tr) - 1):
td = tr[i].select('td')
if td[0].text.strip():
result[0].append(td[0].text.strip()) # 날짜
result[1].append(td[1].text.strip()) # 종가
img = td[2].select('img')
if len(img) != 0:
if 'src' in img[0].attrs:
src = img[0]['src']
if 'up' in src:
result[2].append('상승')
else:
result[2].append('하락')
else:
result[2].append('보합')
result[3].append(td[2].text.strip()) # 전일대비
result[4].append(td[3].text.strip()) # 시장가
result[5].append(td[4].text.strip()) # 최고가
result[6].append(td[5].text.strip()) # 최저가
result[7].append(td[6].text.strip()) # 거래량
return result
def get_market_prices(self, page_num=1):
code = '005930' # 삼성전자
result = self.print_stock_price(code, page_num)
for i in range(len(result[0])):
yyyymm = result[0][i].replace('.', '-') # 날짜
close = result[1][i].replace(',', '') # 종가 (현재가)
open = result[4][i].replace(',', '') # 시가
high = result[5][i].replace(',', '') # 고가
low = result[6][i].replace(',', '') # 저가
trade_qty = result[7][i].replace(',', '') # 거래량
print(code, yyyymm, close, open, high, low, trade_qty)
if __name__ == "__main__":
naver = Naver()
naver.get_market_prices() # 시가종가등 모든 가격을 업데이트
005930 2023-04-14 65100 66600 66600 65000 15477592
005930 2023-04-13 66100 65600 66100 65400 15091022
005930 2023-04-12 66000 65800 66200 65300 15021313
005930 2023-04-11 65900 66200 66200 65400 16323183
005930 2023-04-10 65700 64800 66300 64700 18777166
005930 2023-04-07 65000 63800 65200 63800 27476120
005930 2023-04-06 62300 63500 63600 62300 14992747
005930 2023-04-05 63900 63700 64000 63400 9176149
005930 2023-04-04 63600 63400 63800 62800 11120514
005930 2023-04-03 63100 64000 64000 63000 11973133