Playwright与PyTest结合使用指南

举报
ceshiren001 发表于 2025/08/26 16:56:32 2025/08/26
【摘要】 Playwright与PyTest强强联合,打造高效Web自动化测试方案。前者提供现代化跨浏览器自动化能力,后者带来结构化测试管理与强大扩展性。本文详解二者集成:从环境安装、用例编写、配置执行,到高级技巧如Fixture深度使用、并行测试、页面对象模式及移动端模拟,助你快速构建稳定、可维护的自动化测试体系。

Playwright与PyTest的结合为Web自动化测试注入了强大动能。通过Playwright的现代化跨浏览器自动化功能,又能借助PyTest成熟测试框架的结构化、可扩展性来高效管理和组织测试用例。我会带你了解如何将这两者结合使用。

为了让你快速上手,我先用一个流程图来概括Playwright与PyTest结合使用的核心步骤和关键配置:

企业微信截图_4e131d00-fd2f-4941-90ad-6603ff7075ad.png

下面我们来详细看看各个环节。

🛠️ 安装与环境搭建

首先,你需要安装pytestpytest-playwright插件,并安装Playwright所需的浏览器驱动。

# 1. 安装pytest和pytest-playwright插件
pip install pytest pytest-playwright

# 2. 安装Playwright浏览器驱动(安装较慢,耐心等待)
playwright install

✍️ 编写你的第一个测试用例

创建一个测试文件(如test_example.py),PyTest会自动发现以test_开头的文件或函数。

import pytest
from playwright.sync_api import Page

# 使用page fixture,它由pytest-playwright提供
def test_visit_baidu(page: Page): # 将page fixture作为参数注入
    page.goto("https://www.baidu.com")
    page.fill('//*[@id="kw"]'"Playwright"# 使用XPath定位搜索框并输入
    page.click('#su'# 使用CSS选择器定位并点击“百度一下”按钮
    assert "Playwright" in page.title() # 断言页面标题包含特定文本
    print(page.title) # 打印当前页面标题

⚙️ 配置与执行测试

PyTest-P laywright提供了丰富的命令行参数(CLI)来灵活控制测试行为:

参数 (--)
说明
示例
--headed
有头模式(显示浏览器UI)下运行测试(默认:无头模式)
pytest --headed
--browser
指定浏览器(chromiumfirefoxwebkit)。可多次指定
pytest --browser chromium --browser firefox
--slowmo
减慢操作速度(毫秒),便于观察
pytest --slowmo 1000
--video
录制视频(onoffretain-on-failure
pytest --video on
--screenshot
截屏(onoffonly-on-failure
pytest --screenshot on
--tracing
记录追踪信息(onoffretain-on-failure),用于调试
pytest --tracing on
--numprocesses
使用pytest-xdist进行并行测试
pytest --numprocesses auto

你可以通过pytest.ini文件预设这些参数,避免每次手动输入:

# pytest.ini
[pytest]
addopts = --headed --browser chromium --slowmo 100 --video on --screenshot on

📁 Fixtures的深度使用

Fixtures是PyTest的核心功能,用于设置和清理测试环境。pytest-playwright提供了开箱即用的fixtures。

1. 使用内置Fixtures最常用的是page fixture,它为你提供了一个全新的浏览器页面。

def test_my_app(page: Page):
    page.goto("https://example.com")
    # ... 你的测试逻辑

2. Fixture的作用域 (Scope)Fixtures可以有不同的作用域,控制其创建和销毁的频率。

@pytest.fixture(scope='module') # 该fixture在整个模块中只执行一次
def browser():
    with sync_playwright() as p:
        browser = p.chromium.launch()
        yield browser # 提供浏览器实例给测试用例
        browser.close() # 所有测试完成后关闭浏览器

def test_example_1(browser): # 在不同的测试中复用同一个浏览器实例
    page = browser.new_page()
    # ...

3. 覆盖Fixtures的默认选项你可以自定义浏览器或上下文的启动参数。

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "ignore_https_errors"True# 忽略HTTPS错误

# 或在测试用例中直接标记以覆盖特定上下文的选项
@pytest.mark.browser_context_args(timezone_id="Europe/Berlin", locale="de-DE")
def test_with_custom_timezone(page):
    # 这个测试将在欧洲/柏林时区运行

🧰 高级技巧与最佳实践

  1. 并行测试:使用pytest-xdist插件可以显著缩短大型测试集的运行时间。

    pip install pytest-xdist
    pytest --numprocesses auto # 根据CPU核心数自动创建worker进程
  2. 跳过测试:可以使用PyTest的skip标记根据条件跳过测试。

    import pytest

    @pytest.mark.skip("skip this test for now") # 无条件跳过
    def test_skip_example():
        pass

    @pytest.mark.skip_browser("firefox") # 自定义标记(需实现),跳过特定浏览器
    def test_skip_firefox(page):
        pass
  3. 录制生成代码:Playwright的Codegen功能可以录制你的操作并生成PyTest代码。

    playwright codegen --target python-pytest -o test_recording.py https://baidu.com
  4. 页面对象模式 (Page Object Model):对于复杂项目,强烈建议使用页面对象模式来分离页面元素定位和操作逻辑,提高代码的可维护性和可读性。

    # 示例:一个简单的页面对象
    class BaiduPage:
        def __init__(self, page: Page):
            self.page = page
            self.search_input = page.locator("#kw")
            self.search_button = page.locator("#su")

        def search(self, keyword):
            self.search_input.fill(keyword)
            self.search_button.click()

    # 在测试中使用
    def test_using_pom(page: Page):
        baidu_page = BaiduPage(page)
        baidu_page.search("Playwright")
        # ... 断言
  5. 移动端模拟与多浏览器测试:Playwright可以模拟移动设备,并利用PyTest的参数化功能进行多浏览器测试。

    import pytest
    from playwright.sync_api import sync_playwright

    # 多浏览器参数化测试
    @pytest.mark.parametrize("browser_type", ["chromium", "firefox", "webkit"])
    def test_cross_browser(browser_type):
        with sync_playwright() as p:
            browser = getattr(p, browser_type).launch()
            # ... 测试逻辑
            browser.close()

    # 移动端模拟
    def test_mobile_emulation(playwright):# 使用playwright fixture
        iphone_12 = playwright.devices['iPhone 12 Pro']
        browser = playwright.webkit.launch()
        context = browser.new_context(**iphone_12)
        page = context.new_page()
        page.goto("https://m.example.com")
        # ... 移动端测试逻辑
        browser.close()

💡 常见问题与排查

  • Fixtures未注入:确保测试函数的参数名与fixture名称完全一致(例如page)。
  • 异步与同步API:上述示例均使用同步API。Playwright也支持异步(async/await),如需使用异步,请确保使用async def定义测试函数,并使用from playwright.async_api import Page
  • 元素定位问题:充分利用Playwright强大的定位器(locator),如page.locator('css=button').click(),并配合page.wait_for_selector()等等待方法避免竞态条件。
  • 查看详细输出:运行测试时添加-v-s参数(如pytest -v -s)可以获取更详细的输出和打印语句。

Playwright与PyTest的结合,为你提供了一个功能全面、易于编写且易于维护的现代Web自动化测试方案。从简单的脚本到复杂的企业级测试套件,这个组合都能应对自如。

希望这份指南能帮助你快速上手。实践出真知,多写多试,你就会越来越熟练。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。