输出报告展示
测试环境
- CentOS 7
- Python 3
- Firefox & geckodriver
用到Python 模块
- selenium
- jinja2
- smtplib
项目结构
代码详情
__author__ = 'vito'
# -*- coding:utf-8 -*-
from jinja2 import Environment, FileSystemLoader
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from selenium.webdriver.firefox.options import Options
from selenium import webdriver
from datetime import datetime,timezone,timedelta
import json
import yaml
import os
import time
import smtplib
class EmailMsg():
def send_mail(self, msg):
# 邮件对象:
message = MIMEMultipart()
message.attach(MIMEText(msg, 'html', 'utf-8'))
message['from'] = 'test_from@163.com'
message['to'] = 'test_to@163.com, test_to_2@163.com'
password = "yourpassword"
message['subject'] = Header(u'UI检查', 'utf-8').encode()
smtp_server = "smtp.163.com"
server = smtplib.SMTP_SSL(smtp_server, 465) # SMTP协议SSL端口是465
# 登录SMTP服务器
server.login(message['from'], password)
screen_path = './picture_%s' % time.strftime('%Y-%m-%d', time.localtime())
pics = os.listdir(screen_path)
pics.sort(key=lambda x: int(x.split('.')[0]))
for i in range(len(pics)):
with open('%s/%s' % (screen_path, pics[i]), 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment')
mime.add_header('Content-ID', '<%d>' % i) # 格式化输出多个文件
mime.add_header('X-Attachment-Id', '%d' % i) # 格式化输出多个文件
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
message.attach(mime)
# 发邮件,由于可以一次发给多个人,所以传入一个list;
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
#print('***发送邮件列表***\n', [message['to']])
server.sendmail(message['from'], message['to'].split(','), message.as_string())
server.quit()
def get_yaml_data(yaml_file):
# 打开yaml文件
#print("***获取yaml文件数据***")
file = open(yaml_file, 'r', encoding="utf-8")
file_data = file.read()
file.close()
data = yaml.full_load(file_data)
return data
def capture_screen(url_lst):
res_lst = []
screen_path = './picture_%s' % time.strftime('%Y-%m-%d', time.localtime())
if not os.path.exists(screen_path):
os.makedirs(screen_path)
# 打开浏览器并登陆
options = Options()
options.add_argument('--headless')
browser = webdriver.Firefox(executable_path='./wd/geckodriver', options=options)
browser.get('https://www.baidu.com/')
browser.delete_all_cookies()
with open('./cookies/cookies.txt', 'r') as fp:
cookielist = json.load(fp)
for cookie in cookielist:
if isinstance(cookie.get('expiry'), float):
cookie['expiry'] = int(cookie('expiry'))
browser.add_cookie(cookie)
browser.refresh()
# 遍历URL列表,截图并保存页面数据
for i in range(len(url_lst)):
browser.get(url_lst[i])
time.sleep(3)
title = browser.title
browser.save_screenshot('%s/%s.png' % (screen_path, i))
# 准备数据生成html报告
if title == '':
page_notes = u'页面空白,需手动确认链接'
else:
page_notes = ''
res_dict = {}
res_dict.setdefault('serial_num', i)
res_dict.setdefault('title', title)
res_dict.setdefault('url', url_lst[i])
res_dict.setdefault('page_notes', page_notes)
res_dict.setdefault('screenshot', i)
res_lst.append(res_dict)
browser.back()
browser.close()
return res_lst
if __name__ == '__main__':
# 获取配置文件数据,此处为URL列表
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "config.yaml")
url_list = get_yaml_data(yaml_path)
page_data = capture_screen(url_list)
em = EmailMsg()
env = Environment(loader=FileSystemLoader('./'))
template = env.get_template('./template/template.html')
result = "./result/result_%s.html" % time.strftime('%Y-%m-%d', time.localtime())
dt = datetime.utcnow()
dt = dt.replace(tzinfo=timezone.utc)
tzutc_8 = timezone(timedelta(hours=8))
local_dt = dt.astimezone(tzutc_8)
with open(result, 'w+', encoding='utf-8') as fp:
html_content = template.render(body=page_data,
page_count=len(page_data),
test_time=local_dt.strftime("%Y-%m-%d %H:%M:%S")
)
fp.write(html_content)
em.send_mail(html_content)
配置文件config.yaml
- 'https://www.baidu.com'
- 'https://3g.163.com/touch/#/'
邮件模板
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html align='left'>
<body>
<p><b>检查时间: </b>{{test_time}} </p>
<p><b>检查页面个数:</b><font color="green" >{{page_count}}</font>; </p>
<p><b><font color="black">检查页面详细信息:</font></b></p>
<table border="1" cellspacing='0' cellpadding='0' align='left'>
<tr>
<th width="10%">序号</th>
<th width="15%">页面标题</th>
<th width="20%">页面链接</th>
<th width="15%">页面截图</th>
<th width="15%"><font color="red">问题诊断</font></th>
</tr>
{% for item in body %}
<tr align='center'>
<td>{{ item.serial_num }}</td>
<td>{{ item.title }}</td>
<td align='left'><a href="{{ item.url }}">{{ item.url }}</a></td>
<td><img src="cid:{{item.screenshot}}" alt="页面截图" width="100" height="130"></td>
<td>{{ item.page_notes }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
问题解决
- 问题描述
浏览器中文显示乱码 - 解决办法
yum -y groupinstall Fonts
cookies获取方法可参考https://blog.csdn.net/lylfv/article/details/106853380