gyeomii

🕷Data Crawling 3 본문

개발

🕷Data Crawling 3

gyeomii 2023. 8. 23. 17:58
반응형

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)
    #attr2 = {'width':'60'}
    #price = soup.find_all('td', attrs= attr2)

    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에 자료가 저장된다.

반응형

'개발' 카테고리의 다른 글

📌Web Application Layer  (0) 2023.09.20
JAVA에서 웹 크롤링하기(1)  (0) 2023.08.29
🕷Data Crawling 2  (0) 2023.08.22
🕷Data Crawling 1  (0) 2023.08.22
📈3D Graph2  (0) 2023.07.27