1๋ถ๋ง๋ค .py์คํํด์ DB์ ์๋ฃ ์ ์ฅํ๊ธฐ
์ฝ๋
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from stockdao import StockDao
sd = StockDao()
ymd = datetime.today().strftime("%Y%m%d.%H%M")
url = "https://vip.mk.co.kr/newSt/rate/item_all.php"
response = requests.get(url)
if response.status_code == 200:
html = response.content.decode('euc-kr','replace')
soup = BeautifulSoup(html, 'html.parser')
attr1 = {'class' : 'st2', 'width' : '92'}
tds = soup.find_all('td', attrs = attr1)
count = 0
for idx, td in enumerate(tds):
s_code = td.a['title']
s_name = td.text
price = td.parent.find_all("td")[1].text.replace(",","")
cnt = sd.insert(s_code, ymd, s_name, price)
print(idx+1, "cnt", cnt)
count += 1
print(count, "๊ฐ์ ๋ ์ฝ๋๊ฐ ์
๋ ฅ๋์์ต๋๋ค.")
else :
print(response.status_code)
dao
import pymysql
class StockDao:
def __init__(self):
self.conn = pymysql.connect(host='localhost', port=3305,
user='root', password='python',
db='python', charset='utf8')
self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
def insert(self, s_code, ymd, s_name, price):
sql = f"""
Insert into stock (s_code, ymd, s_name, price)
values ('{s_code}', '{ymd}', '{s_name}', '{price}')
"""
cnt = self.cur.execute(sql)
self.conn.commit()
return cnt
def __del__(self):
self.cur.close()
self.conn.close()
if __name__ == '__main__':
dao = StockDao()
- ์ฐ์ ๋ฐ์ดํฐ๋ฅผ DB์ ์ ์ฅํ ์ ์๋๋ก Insert๋ฅผ ํด์ค๋ค.
- ๊ทธ๋ฆฌ๊ณ .batํ์ผ ์ ๋ง๋ ๋ค.
- ์๋์ฐ ์์
์ค์ผ์ฅด๋ฌ์ 1๋ถ๋ง๋ค .batํ์ผ์ ์คํํ๋๋ก ๋ง๋ ๋ค.
- 1๋ถ๋ง๋ค .batํ์ผ์ด ์คํ๋๋ฉฐ DB์ ์๋ฃ๊ฐ ์ ์ฅ๋๋ค.