Python使用pytest playwright的原因是什么

2023-05-14,,

这篇文章主要介绍了Python使用pytest playwright的原因是什么的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python使用pytest playwright的原因是什么文章都会有所收获,下面我们一起来看看吧。

pytest-playwright 是一个 Python 包,它允许您使用 Microsoft 的 Playwright 库在 Python 项目中进行端到端测试。

1 用playwright能不能不用这个包?

首先田辛老师强调,如果你不想使用 pytest-playwright,你仍然可以在你的 Python 项目中使用 Playwright。只不过需要一些额外的配置。 我们会在下次博客中介绍如何PyUnit+playwright。 下面的代码是一个单纯的playwright的例子

from playwright.sync_api import Playwright, sync_playwright_with_browsers

with sync_playwright_with_browsers() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto('https://www.baidu.com')
    browser.close()

此代码使用 sync_playwright_with_browsers() 函数启动 Playwright 实例,启动 Chromium 浏览器,导航至 Google 主页,然后关闭浏览器。只不过Python不会识别它是一段自动化测试代码, 只是当成一段普通的Python程序去运行。

2 安装

安装方法其实田辛老师在前两天的文档里面提过,通过pip进行安装:
pip install pytest-playwright

3 示例代码

以下是如何使用 pytest-playwright 测试一个简单网站的示例:

import pytest  
from playwright.sync_api import Playwright, sync_playwright  
@pytest.fixture(scope='module')  
def playwright() -> Playwright:  
    with sync_playwright() as playwright:  
        yield playwright  
@pytest.fixture(scope='module')  
def browser(playwright: Playwright):  
    browser = playwright.chromium.launch(headless=False)  
    yield browser  
    browser.close()  
@pytest.fixture(scope='module')  
def page(browser):  
    page = browser.new_page()  
    yield page  
    page.close()  
def test_baidu_homepage(page):  
    page.goto('https://www.baidu.com')  
    assert page.title() == '百度一下,你就知道'

以上的代码使用, 创建一个 Playwright 实例,启动一个 Chromium 浏览器,并创建一个新页面。然后使用 test_baidu_homepage 方法使用 page fixture 导航到网站主页并检查页面标题。

要使用 pytest-playwright 运行此测试,请将代码保存到名为 test_baidu.py 的文件中,然后从命令行运行以下命令:

pytest test_google.py

关于“Python使用pytest playwright的原因是什么”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Python使用pytest playwright的原因是什么”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注本站行业资讯频道。

《Python使用pytest playwright的原因是什么.doc》

下载本文的Word格式文档,以方便收藏与打印。