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

Playwright结合pytest执行时多开空白标签页致测试失败,求优化方法

问题分析与解决方案

问题根源

你遇到的空白标签页超时问题,本质是两套浏览器实例并行运行导致的冲突:

  • pytest.ini 里的 --browser=chromium 配置会让 pytest-playwright 自动初始化一套浏览器上下文和空白页面
  • 你代码里又通过 sync_playwright() 手动创建了另一套浏览器实例
    自动创建的空白页面没有任何操作,最终因超时触发测试失败。

推荐解决方案:利用 pytest-playwright 内置 Fixture(最优)

放弃手动创建浏览器实例,直接使用 pytest-playwright 提供的 page/context Fixture,既避免冲突,又能复用存储状态、简化代码。

步骤1:修改测试函数

将原函数改为标准 pytest 测试函数(以 test_ 开头),通过 Fixture 注入 page:

from playwright.sync_api import expect

def test_navigate_to_edit_page(page):
    # 复用存储状态(跳过重复登录)
    page.context.add_cookies(storage_state="playwright/.auth/storage_login.json")

    # 执行测试步骤
    page.goto("https://example.org/edit")
    page.locator("input#org_name").fill("This is a test!")
    page.get_by_role("button", name="Save").click()
    expect(page.locator(".notice")).to_have_text("Successful update")
    expect(page).to_have_title("New page")

步骤2:全局复用存储状态(可选优化)

如果多个测试都需要复用登录状态,可在 conftest.py 中自定义 Fixture,避免重复代码:

import pytest
from playwright.sync_api import BrowserContext

@pytest.fixture(scope="session")
def context(browser):
    # 初始化上下文时直接加载存储状态
    context = browser.new_context(storage_state="playwright/.auth/storage_login.json")
    yield context
    context.close()

之后测试函数直接使用 page Fixture,会自动继承带登录状态的上下文。


备选方案:禁用 pytest-playwright 自动初始化

若坚持手动创建浏览器实例,需修改 pytest.ini 去掉自动启动浏览器的配置:

addopts = --headed --slowmo=1000

同时调整测试函数(确保是标准 pytest 测试函数),并补充关闭浏览器的步骤:

from playwright.sync_api import sync_playwright, expect
from your_module import BasicAuthentication

def test_navigate_to_edit_page():       
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=1000)
        context = browser.new_context(storage_state="playwright/.auth/storage_login.json")
        page = context.new_page()
        BasicAuthentication.execute(page)
  
        page.goto("https://example.org/edit")
        page.locator("input#org_name").fill("This is a test!")
        page.get_by_role("button", name="Save").click()
        expect(page.locator(".notice")).to_have_text("Successful update")
        expect(page).to_have_title("New page")
        
        context.close()
        browser.close()  # 手动关闭浏览器,避免残留进程

⚠️ 此方案不推荐,会丢失 pytest-playwright 的并行测试、自动资源清理等特性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:32:51