...

Playwright简单入门

Playwright是微软推出的一款WebUI自动化测试框架。

官方文档:https://playwright.dev/python/docs/intro#installing-playwright-pytest

安装方法

pip install pytest-playwright
playwright install

注意:如果使用.venv虚拟环境,可以使用python -m playwright install,把浏览器安装到当前环境中。

打开网页

page.goto("")

元素定位

page.get_by_role("", name="").click()
  • page.get_by_role() to locate by explicit and implicit accessibility attributes.
  • page.get_by_text() to locate by text content.
  • page.get_by_label() to locate a form control by associated label's text.
  • page.get_by_placeholder() to locate an input by placeholder.
  • page.get_by_alt_text() to locate an element, usually image, by its text alternative.
  • page.get_by_title() to locate an element by its title attribute.
  • page.get_by_test_id() to locate an element based on its data-testid attribute (other attributes can be configured).

通过CSS 或 XPath定位

page.locator("css=button").click()
page.locator("xpath=//button").click()

page.locator("button").click()
page.locator("//button").click()

定位frame中元素

locator = page.frame_locator("my-frame").get_by_role("button", name="Sign in")

元素操作

操作 描述
locator.check() 勾选checkbox
locator.click() 点击元素
locator.uncheck() 不勾选checkbox
locator.hover() Hover元素
locator.fill() 输入文字
locator.focus() 聚焦元素
locator.press() 按键
locator.set_input_files() 选择文件
locator.select_option() 选择选项

窗口切换

打开新窗口

new_page = context.new_page()

切换到新的弹出窗口

with context.expect_page() as new_page_info:  
    page.get_by_label("Confirm").get_by_role("button", name="Swap").click()

# 新窗口
new_page = new_page_info.value

断言

expect(page).to_have_title("")
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
断言 描述
expect(locator).to_be_checked() Checkbox is checked
expect(locator).to_be_enabled() Control is enabled
expect(locator).to_be_visible() Element is visible
expect(locator).to_contain_text() Element contains text
expect(locator).to_have_attribute() Element has attribute
expect(locator).to_have_count() List of elements has given length
expect(locator).to_have_text() Element matches text
expect(locator).to_have_value() Input element has value
expect(page).to_have_title() Page has title
expect(page).to_have_url() Page has URL

运行及调试

运行用例-显示浏览器模式

pytest --headed

选择浏览器-支持同时测试多个浏览器

pytest --browser webkit --browser firefox

调试用例

PWDEBUG=1 pytest -s tests/test_usddv2.py

生成用例

playwright codegen https://v2-app-staging.usdd.network/
posted @ 2025-06-25 17:05  韩志超  阅读(65)  评论(0)    收藏  举报