声明:文章中引用的视频为微信群里面的山豆根大佬原创所录制哟~免费视频录制剪辑不易,请大家多多支持。

并且,大佬为这一系列的视频创作还专门购买了服务器搭建了一个实战项目和练习元素定位的网站。网站的具体信息可参考我之前的文章喔:

推荐一个自动化测试练习网站

今日学习笔记

解锁Playwright新技能:单选框、多选框的操作_开发语言

def test_pw_radio(page: Page):
    # 单选框操作
    page.goto("/demo/radio", wait_until="networkidle")
    page.get_by_text("草莓").locator("input").check()
    expect(page.get_by_text("草莓").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("香蕉").locator("input").check()
    expect(page.get_by_text("香蕉").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("苹果").locator("input").check()
    expect(page.get_by_text("苹果").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
def test_pw_checkbox(page: Page):
    # checkbox    check()和set_checked()都可用于选中,也可以用click方法
    page.goto("/demo/checkbox", wait_until="networkidle")
    # page.get_by_text("开发").locator("input").set_checked(True)
    page.get_by_text("开发").locator("input").click()


    expect(page.get_by_text("开发").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("测试").locator("input").set_checked(True)
    expect(page.get_by_text("测试").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("美团").locator("input").set_checked(True)
    expect(page.get_by_text("美团").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)


    page.get_by_text("开发").locator("input").set_checked(False)
    expect(page.get_by_text("开发").locator("input")).not_to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("测试").locator("input").set_checked(False)
    expect(page.get_by_text("测试").locator("input")).not_to_be_checked()
    page.wait_for_timeout(1_000)
    page.get_by_text("美团").locator("input").set_checked(False)
    expect(page.get_by_text("美团").locator("input")).not_to_be_checked()
    page.wait_for_timeout(1_000)


    page.get_by_text("开发").locator("input").check()
    expect(page.get_by_text("开发").locator("input")).to_be_checked()
    page.wait_for_timeout(1_000)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

check、set_checked和click有区别吗?

  1. check():
  • 这个方法用于确保复选框被选中。
  • 如果复选框已经是选中状态,check() 将不会执行任何操作。
  • 如果复选框未被选中,check() 将会模拟点击事件来选中它。
  • check() 可以接收一个布尔值参数,如果传入 false,则会取消选中复选框。

set_checked():

  • 这个方法用于直接设置复选框的选中状态,而不需要模拟点击事件。
  • set_checked() 接受一个布尔值参数,如果传入 true,则设置复选框为选中状态;如果传入 false,则设置为未选中状态。
  • 这个方法跳过了点击动作,直接更改复选框的 checked 属性。

click():

  • 这个方法用于模拟鼠标点击事件。
  • 当你调用 click() 时,Playwright 会模拟一个真实的点击操作,这可能触发页面上的其他事件,如点击事件的监听器。
  • 对于复选框来说,如果点击已经选中的复选框,click() 会取消它的选中状态,反之亦然。

End

关注公众号,测试干货及时送达