我们使用selenium进行元素拖拽时,通常要使用ActionChains来实现drag_and_drop的操作,playwright同样可以实现元素的拖拽和释放的操作。
按住元素从页面的一个位置拖动到另外一个位置,有2种方式可以实现
我们以这个网页为例,介绍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更加简单。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。