摘要
上篇文章介绍如何通过Python+selenium+webdriver实现网页自动登陆,本篇介绍如何解析签到的日志文件以及判断签到是否成功发送邮件。
环境准备
Python 3.8.3 + Pycharm
签到日志文件 执行日志.log
执行日志.log内容格式如下:
2020-09-22 Tuesday 09:05:33 def_logging.py : INFO xxxx开始
2020-09-22 Tuesday 09:05:55 def_logging.py : INFO 签到成功
2020-09-22 Tuesday 09:05:58 def_logging.py : INFO xxxx结束
2020-09-22 Tuesday 09:05:58 def_logging.py : INFO xx开始
2020-09-22 Tuesday 09:06:25 def_logging.py : INFO 签到成功
2020-09-22 Tuesday 09:06:27 def_logging.py : INFO xx结束
2020-09-22 Tuesday 09:06:27 def_logging.py : INFO xxx开始
2020-09-22 Tuesday 09:06:59 def_logging.py : INFO 签到成功
2020-09-22 Tuesday 09:07:03 def_logging.py : INFO xxx结束
实现逻辑
日志关键信息提取
1.每次日志为格式化输出,每天输出9行,读取最后9行日志信息
2.每3行日志为一个分割节点
3.根据每行日志格式,提取最后一个关键字及"xxxx开始","签到成功"类似信息
4.匹配每3行中的第2行作为签到是否成功的标识
邮件发送提示
1.引入发送邮件的相关模块和包
2.定义发送邮件的发送方和接收方
3.定义邮件的发送内容和发送邮件的时机(有签到失败的情况发送)
代码部分
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
fo = open('执行日志.log','r')
lines = fo.readlines()
# 截取最后9行日志信息
lines = lines[-1:-10:-1]
lines.reverse()
i = 1
# seng_flag 决定是否发送邮件 send_msg发送邮件的内容
seng_flag = False
send_msg = ''
for line in lines:
line = line.strip()
if i == 2:
send_msg = send_msg + ':' + line.split()[6] + '\n'
if line.split()[6] == '签到失败':
seng_flag = True
elif i == 3:
i = 0
else:
send_msg = send_msg + line.split()[6]
i += 1
# 关闭文件
fo.close()
from_addr = 'xxxxxxx@qq.com'
password = 'xxxxxxxxxx'
to_addr = 'xxxxxxx@qq.com'
smtp_server = 'smtp.qq.com'
msg = MIMEText(send_msg, 'plain', 'utf-8')
msg['From'] = _format_addr('Administrator ' % from_addr)
msg['To'] = _format_addr('QQ ' % to_addr)
msg['Subject'] = Header('自动签到', 'utf-8').encode()
if seng_flag:
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()