10分钟玩转playwright

乙醇 创建于 over 1 year 之前

最后更新: 7 months 之前

阅读数: 389

playwright初体验

playwright是微软推出的一款自动化测试工具,据说开发小组的核心人员来自google的puppeteer团队,真是一出生就有了个好爹而且好爹的亲爹也是爹中的战斗机,这就让人非常期待了。

下载与安装

playwright应该是使用JavaScript进行开发的,不过考虑到大部分的测试同学可能对python更为熟悉,这里的安装就以python版本为例。

在命令行中输入pip install pytest-playwright,等playwright安装成功之后再输入命令playwright install,这条命令的作用是安装测试所需要的各种浏览器支持,相比较selenium需要先安装浏览器再安装相应版本的driver,playwright的初始化工作就显得轻松了很多。

第一个用例

接下来按照官方文档里的例子我们来跑第一个playwright用例。

新建一个名为test_my_app.py的文件,然后把文档中的例子一字不差的进行拷贝粘贴。

import re
from playwright.sync_api import Page, expect

def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(page: Page):
    page.goto("https://playwright.dev/")

    # Expect a title "to contain" a substring.
    expect(page).to_have_title(re.compile("Playwright"))

    # create a locator
    get_started = page.locator("text=Get Started")

    # Expect an attribute "to be strictly equal" to the value.
    expect(get_started).to_have_attribute("href", "/docs/intro")

    # Click the get started link.
    get_started.click()

    # Expects the URL to contain intro.
    expect(page).to_have_url(re.compile(".*intro"))

然后在命令行里输入pytest,视网速而定,等待个10秒钟左右,就可以看运行结果了。

collected 1 item

test_my_application.py .                                                                                                                       [100%]

================================================================= 1 passed in 7.08s ==================================================================

上面的用例去到了playwright的官网,定位并点击了名为Get Started的链接,最后断言页面上的url里含有intro这个字符串。

1 passed表示运行了1个用例并且用例成功通过。另外默认情况下playwright是以headless的模式运行的,这表示运行的过程中浏览器在后台打开和工作,所以看不到浏览器界面是常规操作,不需要紧张和疑惑。

如果遇到了网络超时的情况,可以试试用下面的用例去替换。

import re
from playwright.sync_api import Page, expect

def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(
    page: Page
):
    page.goto("http://www.itest.info/")

    # Expect a title "to contain" a substring.
    expect(page).to_have_title("重定向科技")

    # create a locator
    plan = page.locator("css=.navbar-nav li >> nth=1 >> a")

    # Expect an attribute "to be strictly equal" to the value.
    expect(plan).to_have_attribute("href", "/plans")

    # Click the get started link.
    plan.click()

    # Expects the URL to contain intro.
    expect(page).to_have_url(re.compile(".*plans"))

脚本录制

playwright支持通过录制的方式生成部分的脚本。

作为爬虫使用

0