BeautifulSoup优化测试报告

一、是什么

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。

中文官方文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

二、目标

提取html报告中的case数(总数/成功/失败),在钉钉通知上显示。

三、代码示例

import requests
import json
from bs4 import BeautifulSoup
import re

file = open('/Users/lk/Desktop/20200729T101237.229802.html', 'rb')
html = file.read()
bs = BeautifulSoup(html, "html.parser")  # 初始化BeautifulSoup对象
a = []
for child in bs.body.table.descendants:  # 获取table子孙节点的内容
    a.append(child.string)
    # print(child.string)
print(a)
print(a[len(a) - 3])
s = str(a[len(a) - 3])  # 获取目标内容,并转换为string
l2 = re.findall(r"d+.?d*", s)  # 正则提取string中的数字,返回列表
print(l2)

# 请求地址
post_url = "https://oapi.dingtalk.com/robot/send?access_token=9de1b6fd05173c3c5622ea6efd1b484413ad95742204649645b16a3f629d7c23"

# 消息头部
headers = {'Content-Type': 'application/json'}

# 消息主体
text = "概要:本次共执行 " + l2[0] + " 个Case,成功 " + l2[1] + " 个,失败 " + l2[2] + """
点击查看HTML测试报告"

data = {
    "msgtype": "link",
    "link": {
        "text": text,
        "title": "接口自动化测试报告",
        "picUrl": "xxx.jpg",
        "messageUrl": "yyy.html"
    }
}

# 使用post请求推送消息
requests.post(post_url, data=json.dumps(data), headers=headers)

四、钉钉通知效果

原文地址:https://www.cnblogs.com/ailiailan/p/13396938.html