본문 바로가기
IT/프로그래밍

파이썬 11번가 봇 만들기 - 내 일을 바꾸는 업무 자동화 13장

by nutrient 2021. 5. 29.
728x90
728x170

 

 

 

13.1

from selenium import webdriver
from openpyxl import Workbook, load_workbook
from os.path import exists
from datetime import datetime
import string

today = datetime.now()
monitor_path = '/Users/Alghost/Downloads/'
today_file_name = '%d_%d_%d.xlsx'%(today.year,today.month,today.day)
file_path = monitor_path + today_file_name

if exists(file_path):
    result_xlsx = load_workbook(file_path)
else:
    result_xlsx = Workbook()

worksheet = result_xlsx.active
worksheet['A2'] = '최근 가격'

opts = webdriver.ChromeOptions()
opts.add_argument('headless')
opts.add_argument('window-size=1920,1080')
driver = webdriver.Chrome(monitor_path+'chromedriver', options=opts)
try:
    product_urls = open(monitor_path+'products.txt', 'r').readlines()
    row =[today.strftime("%H:%M:%S")]
    changes = []
    column_idx = 1
    for product in product_urls:
        driver.get(product)

        price_xpath = "//ul[@class='price_wrap']//dl[@class='price']//span[@class='value']"
        price_tag = driver.find_element_by_xpath(price_xpath)
        row.append(price_tag.text)

        title_tag = driver.find_element_by_xpath("//div[@class='c_product_info_title']/h1")
        column = string.ascii_uppercase[column_idx]
        worksheet[column+'1'] = title_tag.text

        prev_price = worksheet[column+'2'].value
        curr_price = price_tag.text
        if prev_price and prev_price != curr_price:
            changes.append((title_tag.text,prev_price,curr_price))

        worksheet[column+'2'] = price_tag.text
        column_idx += 1

    worksheet.append(row)
    result_xlsx.save(file_path)

    if changes:
        from my_email import send_mail
        contents = str(today)[:-7] + ': 가격이 변동된 상품이 있습니다.\n\n'
        
        for c in changes:
            contents += '(%s) %s => %s\n'%(c[0], c[1], c[2])

        send_mail('이태화', 'alghost.lee@gmail.com', contents)
   
except Exception as e:
    print(e)
finally:
    driver.quit()

 

13.2

import time
from selenium import webdriver
from datetime import datetime, timedelta
from my_email import send_mail

today = datetime.now()
diff = timedelta(days=7)
base_date = today - diff
base_date = base_date.strftime('%Y.%m.%d.')
cron_base = './notice'
opts = webdriver.ChromeOptions()
opts.add_argument('headless')
opts.add_argument('window-size=1920,1080')
driver = webdriver.Chrome('chromedriver', options=opts)

try:
    keywords = open(cron_base+'/keywords.txt', 'r').readlines()
    matches = []

    driver.get('https://www.msit.go.kr/web/msipContents/contents.do?mId=MTAzMA==')
    time.sleep(1)
    elems = driver.find_elements_by_xpath("//div[@class='board_list']/div/a")
    for elem in elems:
        title_tag = elem.find_element_by_class_name('title')
        date_tag = elem.find_element_by_class_name('date')
       
        if date_tag.text > base_date:
            for k in keywords:
                if k.strip() in title_tag.text:
                    matches.append(f'{date_tag.text}: {title_tag.text}')
                    break

    if matches:
        contents = '최근 올라온 공고가 있습니다.\n\n'

        contents += '\n'.join(matches)
        send_mail('이태화', 'alghost.lee@gmail.com', contents)

except Exception as e:
    print(e)
finally:
    driver.quit()

 

13.3-1

from datetime import datetime

today = datetime.now()
print(today)

 

13.3-2

from datetime import datetime

today = datetime.now()
print(today.year)
print(today.month)
print(today.day)
print(today.hour)
print(today.minute)
print(today.second)

 

13.3-3

from datetime import datetime

today = datetime.now()
print(today.strftime('%Y-%m-%d %H:%M:%S'))

 

my_email.py

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP_SSL

SMTP_SERVER = 'smtp.naver.com'
SMTP_PORT = 465
SMTP_USER = 'lthlovelee@naver.com'
# 실제 비밀번호를 입력해야 합니다.
SMTP_PASSWORD = ''


def send_mail(name, addr, contents, attachment=False):
    msg = MIMEMultipart('alternative')

    if attachment:
        msg = MIMEMultipart('mixed')

    msg['From'] = SMTP_USER
    msg['To'] = addr
    msg['Subject'] = name + '님, 메일이 도착했습니다.'

    text = MIMEText(contents)
    msg.attach(text)

    if attachment:
        from email.mime.base import MIMEBase
        from email import encoders

        file_data = MIMEBase('application', 'octet-stream')
        f = open(attachment, 'rb')
        file_contents = f.read()
        file_data.set_payload(file_contents)
        encoders.encode_base64(file_data)

        from os.path import basename
        filename = basename(attachment)
        file_data.add_header('Content-Disposition',
                'attachment', filename=filename)
        msg.attach(file_data)

    smtp = SMTP_SSL(SMTP_SERVER, SMTP_PORT)
    smtp.login(SMTP_USER, SMTP_PASSWORD)
    smtp.sendmail('lthlovelee@naver.com', addr, msg.as_string())
    smtp.close()

 

keywords.txt
0.00MB
products.txt
0.00MB

728x90
그리드형

댓글