playwirght使用(一)

playwright 使用

  • 电脑 Mac M1
  • 编辑器Vscode
  • python 3.8.12

安装

  1. 新建项目文件夹

    mkdir playwright-python

    cd playwirght-python

  2. 新建虚拟环境

    python -m venv pw-venv

  3. 激活虚拟环境

    source pw-venv/bin/activate

  4. 安装playwright

    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytest-playwright

  5. 安装浏览器

    playwright install

运行第一个文件

根目录新建文件test_example.py(需要test_开头,因为运行pytest命令时,会自动执行test_开头的文件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import re
from playwright.sync_api import Page, expect

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

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

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

# Click the get started link.
page.get_by_role("link", name="Get started").click()

# Expects page to have a heading with the name of Installation.
expect(page.get_by_role("heading", name="Installation")).to_be_visible()

在终端上运行pytest,此语句会执行test文件