抛开pytest,单单使用playwright打开一个浏览器访问百度
不用pytest-playwright提供的page
pytest使用的时候特别简单直接在用例中添加一个page fixture就可以使用了,如果我们想自己直接调用playwrght怎么办?官网:https://playwright.dev/python/docs/library#usage
playwright提供的浏览器操作
访问网址
page.goto(url)
有头\无头浏览器
browser = playwright.chromium.launch(headless=False)
#打开
browser = playwright.chromium.launch(headless=True)
#关闭
点击按钮
page.get_by_label('I agree to the terms above').check()
# 单击
page.get_by_text("Item").click(button="right")
# 右击
page.get_by_text("Item").dblclick()
# 双击
page.get_by_text("Item").click(modifiers=["Shift"])
# shift + 单击
page.get_by_text("Item").hover()
# 鼠标悬浮
page.get_by_text("Item").click(position={ "x": 0, "y": 0})
# 根据元素文件点击 !!! 非常好用
assert page.get_by_label('Subscribe to newsletter').is_checked() is True # 判断按钮是否已经点击针对单选框或者多选
聚焦
page.get_by_label('password').focus()
按键盘操作
page.get_by_text("Submit").press("Enter")
page.locator('#name').press('Shift+A')
截图
page.screenshot(path="example.png")
等待
page.wait_for_timeout(5000) # 这里是毫秒
输入文本
page.locator("#kw").fill("playwright")
如果无法输入请使用page.locator('#area').type('Hello World!')
#模拟键盘输入
大多数情况下fill
都可以满足。
元素定位
https://playwright.dev/python/docs/locators
page.locator("#kw").click()
# 通过id定位
page.locator("css=button").click()
page.locator("xpath=//button").click()
page.locator("button").click()
page.locator("//button").click()
上传文件
page.get_by_label("Upload file").set_input_files('myfile.pdf')
page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
上传失败用这个
with page.expect_file_chooser() as fc_info:
page.get_by_text("Upload").click()
file_chooser = fc_info.value
file_chooser.set_files("myfile.pdf")
下载文件
以上操作对元素要有要求限制的
- 比如点击操作,要求元素:可见、稳定的、可接受事件的
判断元素
断言
playwright 本身提供的功能
生成代码块
playwright codegen www.baidu.com
通过点击浏览器页面,右边框中自动生成python代码
用例执行追踪
查看执行记录
playwright show-trace trace.zip