前言
鼠标为我们使用电脑提供了很多方便,我们看到的东西就可以将鼠标移动过去进行点击就可以打开或者访问内容,当页面内容过长时,我们也可以使用鼠标滚轮来实现对整个页面内容的查看,其实playwright也有鼠标操作的方法,本文我们就来介绍playwright的鼠标操作。
鼠标操作
Mouse 鼠标操作是基于page对象去调用,常用的鼠标操作有单击,双击,滚轮,按住,移动,释放。
- page.mouse 使用
Mouse 类在相对于视口左上角的主框架 CSS 像素中运行。
每个page对象都有自己的鼠标,可通过page.mouse访问。语法示例如下:
page.mouse.move(0, 0)
page.mouse.down()
page.mouse.move(0, 100)
page.mouse.move(100, 100)
page.mouse.move(100, 0)
page.mouse.move(0, 0)
page.mouse.up()
- click 点击
鼠标click 点击是mouse.move()、mouse.down()、mouse.up()的快捷方式,方法源码如下:
def click(
self,
x: float,
y: float,
*,
delay: typing.Optional[float] = None,
button: typing.Optional[Literal["left", "middle", "right"]] = None,
click_count: typing.Optional[int] = None
) -> None:
"""Mouse.click
Shortcut for `mouse.move()`, `mouse.down()`, `mouse.up()`.
Parameters
----------
x : float
y : float
delay : Union[float, None]
Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
button : Union["left", "middle", "right", None]
Defaults to `left`.
click_count : Union[int, None]
defaults to 1. See [UIEvent.detail].
"""
参数说明:
- x 横向坐标位置
- y 纵向坐标位置
- delay 是mousedown 和 mouseup 事件中间的等待时间,单位是毫秒,默认是0
- button 是点击元素的位置:"left", "middle", "right", 默认参数是left
- click_count 是点击次数
mouse.click(x, y)
mouse.click(x, y, **kwargs)
- dblclick 双击
鼠标双击是mouse.move()、mouse.down()、mouse.up()、mouse.down()和mouse.up()的快捷方式,语法如下:
mouse.dblclick(x, y)
mouse.dblclick(x, y, **kwargs)
- mouse.down 按住鼠标
调度一个mousedown事件。
参数说明:
- button 是点击元素的位置:"left", "middle", "right", 默认参数是left
- click_count 是点击次数
语法示例:
mouse.down()
mouse.down(**kwargs)
- mouse.move 移动
调度一个鼠标移动事件,源码如下:
def move(self, x: float, y: float, *, steps: typing.Optional[int] = None) -> None:
"""Mouse.move
Dispatches a `mousemove` event.
Parameters
----------
x : float
y : float
steps : Union[int, None]
Defaults to 1. Sends intermediate `mousemove` events.
"""
语法如下:
mouse.move(x, y)
mouse.move(x, y, **kwargs)
- wheel 滚轮
调度一个wheel事件。(滚轮事件如果不处理可能会导致滚动,该方法不会等待滚动结束才返回。),语法如下:
mouse.wheel(delta_x, delta_y)
实例
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://sahitest.com/demo/clicks.htm")
# 单击
page.get_by_role("button", name="click me", exact=True).click()
# 双击
page.get_by_role("button", name="dbl click me").dblclick()
# 右击
page.get_by_role("button", name="right click me").click(button="right")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
总结
本文主要介绍了playwright的鼠标操作,希望可以帮到大家。
标签:web,None,playwright,鼠标,move,page,mouse,click,软件测试 From: https://www.cnblogs.com/hogwarts/p/17609627.html