前言
我们使用selenium进行元素拖拽时,通常要使用ActionChains来实现drag_and_drop的操作,playwright同样可以实现元素的拖拽和释放的操作。
按住元素从页面的一个位置拖动到另外一个位置,有2种方式可以实现
- locator.drag_to(target: locator) 先定位元素,调用drag_to方法到目标元素
- page.drag_and_drop(source: str, target: str) page对象直接调用
示例场景
我们以这个网页为例,介绍playwright的元素拖拽和释放的操作,网页地址:https: //sahitest.com/demo/dragDropMooTools.htm, 页面如下:
拖拽操作
locator.drag_to()可以实现拖放操作,该操作将:
- 将鼠标悬停在要拖动的元素上
- 按鼠标左键
- 将鼠标移动到将接收放置的元素
- 松开鼠标左键
语法示例:
page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))
示例如下:
from playwright.sync_api import Playwright, sync_playwright, expect
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/dragDropMooTools.htm")
page.locator("#dragger").drag_to(page.locator("text=Item 1"))
page.pause()
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
拖动和释放操作
page.drag_and_drop可以实现通过page对象调用drag_and_drop ,部分源码如下:
def drag_and_drop(
self,
source: str,
target: str,
*,
source_position: typing.Optional[Position] = None,
target_position: typing.Optional[Position] = None,
force: typing.Optional[bool] = None,
no_wait_after: typing.Optional[bool] = None,
timeout: typing.Optional[float] = None,
strict: typing.Optional[bool] = None,
trial: typing.Optional[bool] = None
) -> None:
注:source 和 target 是字符串格式,也就是传selector 选择器的方法
语法如下:
page.drag_and_drop(locator, loacator)
from playwright.sync_api import Playwright, sync_playwright, expect
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/dragDropMooTools.htm")
page.drag_and_drop('#dragger', 'text=Item 2')
page.pause()
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
运行脚本,结果如下图:
鼠标拖动
想精确控制拖动操作,可以使用较低级别的方法,如locator.hover()、mouse.down()、mouse.move()和mouse.up()。代码如下:
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.get_by_text('Drag me').hover()
page.mouse.down()
page.locator('text=Item 3').hover()
page.mouse.up()
page.pause()
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
运行脚本,界面如下所示:
总结
本文主要介绍了playwright的元素拖拽和释放操作,与selenium一样,playwright同样支持元素拖拽操作,不过playwright的拖拽操作比selenium更加简单。