抛开pytest,单单使用playwright打开一个浏览器访问百度

不用pytest-playwright提供的page

pytest使用的时候特别简单直接在用例中添加一个page fixture就可以使用了,如果我们想自己直接调用playwrght怎么办?官网:https://playwright.dev/python/docs/library#usage
image

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都可以满足。
image

元素定位

https://playwright.dev/python/docs/locators
image

page.locator("#kw").click() # 通过id定位
page.locator("css=button").click()
page.locator("xpath=//button").click()
page.locator("button").click()
page.locator("//button").click()
image

上传文件

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")

下载文件

  • image

以上操作对元素要有要求限制的

  • 比如点击操作,要求元素:可见、稳定的、可接受事件的
    image

判断元素

  • image

断言

  • image

playwright 本身提供的功能

生成代码块

playwright codegen www.baidu.com
image
通过点击浏览器页面,右边框中自动生成python代码

用例执行追踪

image
查看执行记录
playwright show-trace trace.zip
image

posted @   Tarzen  阅读(313)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2020-07-06 Pycharm导包报错解决办法
2020-07-06 Python中i使用ini配置文件
2020-07-06 Python获取Linux的家目录
点击右上角即可分享
微信分享提示