You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动化提取Newman与SeleniumBase报告数据并填充至模板?

自动化整合API与UI测试报告的解决方案

问题根源

你之前的脚本返回空结果,核心原因是选择器与目标报告的HTML结构不匹配:

  • SeleniumBase的报告基于pytest-html,测试结果行的class是test-row,而非你脚本中指定的col-name(col-name是测试名称所在<td>的class)
  • Scrapy脚本中的CSS选择器.test-name、.test-status在实际报告中不存在,导致无法定位元素

实现思路

放弃手动截图粘贴的方式,改为提取结构化数据+统一生成报告,步骤如下:

  1. 分别解析SeleniumBase(UI)和Newman(API)的原始报告,提取测试名称、状态、耗时等核心数据
  2. 将两类数据统一格式
  3. 用模板引擎生成整合后的QA总报告(支持HTML/Excel/PDF格式)

修正后的实现脚本

1. 解析SeleniumBase(UI)测试报告

from bs4 import BeautifulSoup

def parse_seleniumbase_report(file_path):
    test_data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        soup = BeautifulSoup(file, 'html.parser')
        # 定位pytest-html中的测试结果行
        test_rows = soup.find_all('tr', class_='test-row')
        for row in test_rows:
            # 提取测试名称
            test_name_elem = row.find('td', class_='col-name').find('a')
            test_name = test_name_elem.text.strip() if test_name_elem else '未知测试'
            # 提取测试状态
            status_elem = row.find('td', class_='col-result').find('span')
            test_status = status_elem.text.strip() if status_elem else '未知状态'
            # 提取测试耗时
            duration_elem = row.find('td', class_='col-duration')
            test_duration = duration_elem.text.strip() if duration_elem else '0s'
            
            test_data.append({
                'type': 'UI测试',
                'name': test_name,
                'status': test_status,
                'duration': test_duration
            })
    return test_data

2. 解析Newman(Postman API)测试报告

Newman支持直接生成JSON格式报告,无需解析HTML,效率更高:

import json

def parse_newman_report(file_path):
    test_data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        report_data = json.load(file)
        for execution in report_data['run']['executions']:
            test_name = execution['item']['name']
            # 判断测试是否通过(所有断言无错误则为通过)
            test_status = '通过' if all(assertion['error'] is None for assertion in execution['assertions']) else '失败'
            test_duration = f"{execution['response']['responseTime']}ms"
            
            test_data.append({
                'type': 'API测试',
                'name': test_name,
                'status': test_status,
                'duration': test_duration
            })
    return test_data

3. 生成整合后的QA总报告

使用Jinja2模板引擎生成美观的HTML报告(先执行pip install jinja2安装依赖):

第一步:创建报告模板(命名为qa_report_template.html)

<!DOCTYPE html>
<html>
<head>
    <title>QA总测试报告</title>
    <style>
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        th { background-color: #f5f5f5; font-weight: bold; }
        .passed { color: #2ecc71; font-weight: bold; }
        .failed { color: #e74c3c; font-weight: bold; }
        .summary { padding: 15px; background-color: #f9f9f9; border-radius: 5px; }
        .summary p { margin: 5px 0; }
        h1, h2 { color: #333; }
    </style>
</head>
<body>
    <h1>QA总测试报告</h1>
    <div class="summary">
        <p>总测试用例数: {{ total_tests }}</p>
        <p>通过数: {{ passed_tests }} ({{ passed_percent }}%)</p>
        <p>失败数: {{ failed_tests }} ({{ failed_percent }}%)</p>
    </div>
    <h2>测试详情</h2>
    <table>
        <tr>
            <th>测试类型</th>
            <th>测试名称</th>
            <th>状态</th>
            <th>耗时</th>
        </tr>
        {% for test in all_tests %}
        <tr>
            <td>{{ test.type }}</td>
            <td>{{ test.name }}</td>
            <td class="{{ 'passed' if test.status == '通过' else 'failed' }}">{{ test.status }}</td>
            <td>{{ test.duration }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

第二步:编写生成报告的脚本

from jinja2 import Environment, FileSystemLoader
import os

def generate_qa_report(ui_tests, api_tests, output_path):
    all_tests = ui_tests + api_tests
    total_tests = len(all_tests)
    passed_tests = len([t for t in all_tests if t['status'] in ['通过', 'PASSED']])
    failed_tests = total_tests - passed_tests
    passed_percent = round((passed_tests / total_tests) * 100, 2) if total_tests > 0 else 0
    failed_percent = round((failed_tests / total_tests) * 100, 2) if total_tests > 0 else 0
    
    # 加载模板文件
    env = Environment(loader=FileSystemLoader(os.path.dirname(output_path)))
    template = env.get_template('qa_report_template.html')
    
    # 渲染模板并写入文件
    report_content = template.render(
        all_tests=all_tests,
        total_tests=total_tests,
        passed_tests=passed_tests,
        failed_tests=failed_tests,
        passed_percent=passed_percent,
        failed_percent=failed_percent
    )
    
    with open(output_path, 'w', encoding='utf-8') as file:
        file.write(report_content)

# 示例执行
if __name__ == '__main__':
    # 解析两类报告
    ui_test_data = parse_seleniumbase_report('sbase_report.html')
    api_test_data = parse_newman_report('newman_report.json')
    # 生成总报告
    generate_qa_report(ui_test_data, api_test_data, 'qa_summary_report.html')

完整执行流程

  1. 生成原始报告
    • 运行SeleniumBase测试并生成HTML报告:pytest --html=sbase_report.html
    • 运行Newman测试并生成JSON报告:newman run your_postman_collection.json -r json --reporter-json-export newman_report.json
  2. 执行整合脚本:运行上述Python脚本,生成qa_summary_report.html
  3. 可选:转成PDF:使用wkhtmltopdf工具将HTML报告转为PDF:wkhtmltopdf qa_summary_report.html qa_summary_report.pdf

内容的提问来源于stack exchange,提问作者mastafadhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:22:52