파이썬 코드

이용표·2022년 4월 30일
0

출퇴근 자동화

목록 보기
2/4
post-thumbnail

파이썬 코드


import email #
import selenium # 크롬 웹 브라우저 99.0.4844.74 , 82
import time 
import smtplib # 메일
import random # 랜덤
import sys # 스케줄러
from email.mime.text import MIMEText
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from loguru import logger #로그

logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}") #로그 추출

# 인원
accounts = [
    {
        # 인원1
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    },
    {
        # 인원2
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    },
    {
        # 인원3
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    },
    {
        # 인원4
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    },
    {
        # 인원5
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    },
    {
        # 인원6
        "id" : "ID",
        "pwd" : "PWD",
        "email" : "E-mail"
    }
]
accounts_random=random.sample(accounts,len(accounts)) # 랜덤 함수

MAIL_TYPE_WORK = 1
MAIL_TYPE_HOME = 2
MAIL_TYPE_WORK_ERROR = 3
MAIL_TYPE_HOME_ERROR = 4

# 메일 함수
def send_mail(mail_type, to):
    subject = '출근' if mail_type == MAIL_TYPE_WORK else '퇴근' # 제목 : mail_type가 mail_type_work가 같으면 출근 아니면 퇴근
    content = '정상 출근입니다. 확인 부탁드립니다.' if mail_type == MAIL_TYPE_WORK else '정상 퇴근입니다. 확인 부탁드립니다.' # 내용 : mail_type가 mail_type_work가 같으면 출근메시지 아니면 퇴근메시지

    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.starttls()  # TLS 사용시 필요
    smtp.login('발신 메일', '발신 메일 패스워드')
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['To'] = to
    smtp.sendmail('발신 메일', to , msg.as_string())
    smtp.quit()
    
# 에러 메일 함수
def send_mail_Error(mail_type, to):
    subject = '출근_에러' if mail_type == MAIL_TYPE_WORK_ERROR else '퇴근_에러' # 제목 : mail_type가 mail_type_work가 같으면 출근 아니면 퇴근
    content = '에러가 발생 하였습니다. 직접 확인 부탁드립니다.' if mail_type == MAIL_TYPE_WORK_ERROR else '에러가 발생 하였습니다. 직접 확인 부탁드립니다.' # 내용 : mail_type가 mail_type_work가 같으면 출근메시지 아니면 퇴근메시지

    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.starttls()  # TLS 사용시 필요
    smtp.login('발신 메일', '발신 메일 패스워드')
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['To'] = to
    smtp.sendmail('발신 메일', to , msg.as_string())
    smtp.quit()

# 홈페이지 접속 함수
def go_homepage():
    driver.get("http://gw.yottatech.co.kr/") # url로 이동
    driver.implicitly_wait(10) #10초 동안 대기이지만 그 전에 실행 창이 뜨면 실행 가능
    driver.maximize_window() # 화면 최대화

# 로그인 함수
def login(id, pwd):
    driver.implicitly_wait(10) #10초 동안 대기이지만 그 전에 실행 창이 뜨면 실행 가
    time.sleep(0.5)
    #if driver.find_element_by_xpath('//*[@id="popup_area"]/div[2]') :
    #    time.sleep(0.5) # 0.5초 대기
    #    driver.find_element_by_xpath('//*[@id="popup_area"]/div[2]/a').click()
    driver.find_element_by_xpath('//*[@id="emp_no"]').send_keys(id) #ID 입력
    driver.find_element_by_xpath('//*[@id="passwd"]').send_keys(pwd) #패스워드 입력
    driver.find_element_by_xpath('//*[@id="login"]/fieldset/div[1]/ul[3]/li[1]/a').click() # 로그인 클릭
    


# 로그아웃 함수
def logout():
    driver.implicitly_wait(30) #30초 동안 대기이지만 그 전에 실행 창이 뜨면 실행 가능

    driver.switch_to.frame('headerframe') # 로그오프 iframe 들어가기
    driver.find_element_by_xpath('//*[@id="frm"]/div[2]/ul[2]/li[2]/a/img').click() # 로그오프 클릭
    driver.switch_to.default_content() # 초기 iframe으로 나오기

# 팝업 삭제
def popup():
    go_homepage() # 홈페이지 접속
    for account in accounts_random:
        try :
            login(account["id"], account["pwd"]) # login 함수로 들어가 id 와 pwd 순서대로 입력  
            driver.implicitly_wait(10) 
            driver.switch_to.frame('popupframe') # 출근 iframe 들어가기
            time.sleep(1)
            driver.find_element_by_xpath('//*[@id="popup_area"]/div[3]/p/label').click() # 다신 안보기
            driver.implicitly_wait(10) 
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            logout() # 로그아웃
        except Exception as error:
            print("에러발생", error)
            logger.error(error)
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            driver.implicitly_wait(10)
            logout() # 로그아웃
            
# 출근 함수 
def go_work():
    go_homepage() # 홈페이지 접속
    for account in accounts_random:
        try :
            login(account["id"], account["pwd"]) # login 함수로 들어가 id 와 pwd 순서대로 입력  
            time.sleep(random.randint(15,30))  # 15 ~30초 랜덤
            driver.switch_to.frame('bodyframe') # 출근 iframe 들어가기
            time.sleep(1)
            driver.find_element_by_xpath('//*[@id="frm"]/div/div[1]/div[1]/div[2]/div/div[2]/div[1]/ul/li[1]/a').click() # 출근 버튼 클릭
            time.sleep(2) #3초 대기 
            driver.switch_to.alert.accept() #팝업 클릭
            driver.implicitly_wait(10) #10초 동안 대기이지만 그 전에 실행 창이 뜨면 실행 가능
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            logout() # 로그아웃
            send_mail(MAIL_TYPE_WORK, account["email"]) # 메일 보내기
        except Exception as error:
            print("에러발생", error)
            logger.error(error)
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            logout() # 로그아웃
            send_mail_Error(MAIL_TYPE_WORK_ERROR, account["email"]) # 메일 보내기
# 퇴근 함수
def go_home() :
    go_homepage() # 홈페이지 접속
    for account in accounts_random:
        try : 
            login(account["id"], account["pwd"]) # login 함수로 들어가 id 와 pwd 순서대로 입력
            time.sleep(random.randint(15,30))  # 15 ~30초 랜덤           
            driver.switch_to.frame('bodyframe') # 퇴근 iframe 들어가기  
            time.sleep(1)                          
            driver.find_element_by_xpath('//*[@id="frm"]/div/div[1]/div[1]/div[2]/div/div[2]/div[1]/ul/li[2]/a').click() # 퇴근 버튼 클릭
            time.sleep(2) #3초 대기 
            driver.switch_to.alert.accept() #팝업 클릭
            driver.implicitly_wait(10) #10초 동안 대기이지만 그 전에 실행 창이 뜨면 실행 가능           
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            logout() # 로그아웃
            send_mail(MAIL_TYPE_HOME, account["email"]) # 메일 보내기
        except Exception as error:
            print("에러발생", error)
            logger.error(error)
            driver.switch_to.default_content() # 초기 iframe으로 나오기
            logout() # 로그아웃
            send_mail_Error(MAIL_TYPE_HOME_ERROR, account["email"]) # 메일 보내기

if __name__ == '__main__':
    driver = webdriver.Chrome('C:/XXX/XXXX/XXXXX/XXXXXX/chromedriver') # 웹 드라이버 생성
    work_type=sys.argv[1] # 파이썬 인자값 받기
    if work_type == 'work': # work 입력시 go_work () 실행
        go_work()
    elif work_type == 'popup': # popup 입력시 popup() 실행
        popup()    
    else : # 나머지 go_home() 실행
        go_home()
    driver.quit() #크롬 드라이버 종료


profile
바보 개발자 지망생

0개의 댓글