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

如何在Selenium Python与Pytest中遇失败后持续执行并上报失败用例?

在Selenium+Pytest环境中实现失败不终止并标记失败的方法

场景1:多个测试用例,单个用例失败后继续执行其余用例

Pytest默认就支持这种行为——只要你不使用 -x(或 --exitfirst)参数运行测试,就算某个用例失败,Pytest也会跑完所有用例,并且在测试报告里把失败的用例明确标记出来。

如果你之前的运行命令加了 -x,去掉它就行,正常运行命令如下:

pytest your_test_file.py

场景2:单个测试用例内部,某步骤失败后继续执行后续步骤,最终标记用例失败

这种情况需要你控制测试内的断言/步骤失败逻辑,推荐用 pytest-check 插件来简化操作,它能让你在测试中执行多个检查,就算前面的检查失败,后面的步骤也会继续跑,最后汇总所有失败点。

步骤1:安装插件

pip install pytest-check

步骤2:在测试代码中使用

示例代码:

import pytest
from selenium import webdriver
import pytest_check as check

def test_web_ui_flow():
    driver = webdriver.Chrome()
    driver.get("https://example.com")

    # 检查页面标题,失败不终止
    check.equal(driver.title, "Example Domain", "页面标题不匹配")
    
    # 继续执行后续操作
    driver.find_element("css selector", "a").click()
    
    # 检查跳转后的URL
    check.equal(driver.current_url, "https://www.iana.org/domains/example", "URL跳转错误")
    
    driver.quit()

如果不想用插件,也可以自己通过异常捕获来实现:

import pytest
from selenium import webdriver

def test_web_ui_flow():
    driver = webdriver.Chrome()
    driver.get("https://example.com")
    test_failed = False

    # 第一个检查点
    try:
        assert driver.title == "Example Domain"
    except AssertionError:
        test_failed = True
        print("错误:页面标题不匹配")

    # 继续执行点击操作
    try:
        driver.find_element("css selector", "a").click()
    except Exception as e:
        test_failed = True
        print(f"错误:点击链接失败 - {str(e)}")

    # 第二个检查点
    try:
        assert driver.current_url == "https://www.iana.org/domains/example"
    except AssertionError:
        test_failed = True
        print("错误:URL跳转不符合预期")

    driver.quit()

    # 最后统一标记用例失败
    if test_failed:
        pytest.fail("测试流程中存在失败步骤", pytrace=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:09:28