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

如何在Python pytest html报告中添加截图并解决运行报错问题

问题根源说明

你遇到的两个报错均是对象获取逻辑错误导致的:

  • 第一个KeyError: 'request':通过item.funcargs获取request的方式仅在测试用例显式声明依赖request fixture时生效,兼容性极差;同时你定义的webdriver fixture名为setup,代码中却尝试获取名为browser的fixture,名称不匹配也会导致报错。
  • 第二个NameError: name 'driver' is not defined:pytest_runtest_makereport hook函数作用域内未定义driver变量,也没有从测试上下文获取webdriver实例的逻辑,直接调用driver.save_screenshot自然找不到对象。

修复后完整代码

import os
import base64
from datetime import datetime
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


# webdriver fixture 保持和你原路径一致,fixture名如果改了后面对应修改
@pytest.fixture()
def setup():
    chrome_options = Options()
    # 可以加无头配置防止运行时弹出浏览器
    # chrome_options.add_argument("--headless=new")
    driver = webdriver.Chrome(
        executable_path=r'E:\Python Projects\StackField\testCases\chromedriver.exe',
        options=chrome_options
    )
    yield driver
    # 测试结束后自动关闭浏览器
    driver.quit()


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin("html")
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, "extra", [])
    
    # 仅在用例执行阶段处理
    if report.when == "call":
        # 通用添加url逻辑
        extra.append(pytest_html.extras.url("https://sprint.moravis.com/run/val/adchef/a0bfkgb"))
        xfail = hasattr(report, "wasxfail")
        
        # 用例失败/xfail跳过场景添加截图
        if (report.skipped and xfail) or (report.failed and not xfail):
            # 从测试上下文获取webdriver实例,fixture名和上面定义的保持一致为setup
            driver = item._request.getfixturevalue("setup")
            timestamp = datetime.now().strftime('%H-%M-%S')
            
            # 兼容--self-contained-html参数,将截图转base64嵌入报告
            screenshot_base64 = driver.get_screenshot_as_base64()
            html = f'''
            <div>
                <img src="data:image/png;base64,{screenshot_base64}" alt="screenshot" 
                     style="width:300px;height:200px" onclick="window.open(this.src)" align="right"/>
            </div>
            '''
            extra.append(pytest_html.extras.html(html))
        
        report.extra = extra


def pytest_html_report_title(report):
    report.title = "Stackfield report"

运行说明

使用你原有命令即可正常生成带失败截图的报告:
pytest --html=report.html --self-contained-html testCases/test_basic.py

注意事项

  • 如果你将webdriver fixture的名称从setup改为其他值,需要同步修改getfixturevalue("setup")中的fixture名称
  • 代码中已添加测试结束自动关闭浏览器的逻辑,无需额外手动处理
  • 截图直接转base64嵌入报告,无需本地存储,完全兼容--self-contained-html参数,报告分享后其他人也能正常查看截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:30:04