前言

SVG英文全称为Scalable vector Graphics,意思为可缩放的矢量图,这种元素比较特殊,需要通过 ​name​() 函数来进行定位。
本篇讲下关于svg元素的拖拽相关操作。

拖拽 svg 元素

如图所示,svg下的circle元素是可以拖动的

比如往右拖动 100 个像素, 那么cx的值由原来的cx="100"变成 cx="200"

通过鼠标是可以实现拖拽操作的

playwright 拖拽 svg 元素

先定位目标元素,通过 mouse 鼠标事件操作

from playwright.sync_api import sync_playwright
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto('file:///C:/Users/dell/Desktop/drag/snap_events.html')

    # svg元素定位
    circle = page.locator('//*[name()="svg"]/*[name()="circle"]')
    print(circle.bounding_box())
    box = circle.bounding_box()
    # svg元素拖拽
    page.mouse.move(x=box['x']+box['width']/2, y=box['y']+box['height']/2)
    page.mouse.down()
    page.mouse.move(x=box['x']+box['width']/2+100, y=box['y']+box['height']/2)
    page.mouse.up(button="middle")

如果不确定鼠标down事件有没触发,可以加个元素的事件监听,看console日志

from playwright.sync_api import sync_playwright
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/


with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto('file:///C:/Users/dell/Desktop/drag/snap_events.html')

    # svg元素定位
    circle = page.locator('//*[name()="svg"]/*[name()="circle"]')
    print(circle.bounding_box())
    box = circle.bounding_box()
    # 添加事件监听
    circle.evaluate('node => node.addEventListener("mousedown", function(){console.log("目标元素被鼠标down了");});')

    # svg元素拖拽
    page.mouse.move(x=box['x']+box['width']/2, y=box['y']+box['height']/2)
    page.mouse.down()
    page.mouse.move(x=box['x']+box['width']/2+100, y=box['y']+box['height']/2)
    page.mouse.up(button="middle")

文章转自:https://www.cnblogs.com/yoyoketang/p/17357453.html