如何拖放 Selenium (例子)

⚡ 智能摘要

拖放 Selenium WebDriver 能够自动模拟基于鼠标的交互,将源元素移动到指定目标位置并释放。Actions 类通过 dragAndDrop 和 dragAndDropBy 方法实现这些手势,从而实现精确、可重复的浏览器自动化操作。

  • 🎓 使用 Actions 类构建键盘和鼠标手势,然后调用 build() 和 perform() 在页面上执行它们。
  • 🌟 当源元素和目标元素都存在时,请选择 dragAndDrop(源元素, 目标元素);当需要像素级精度时,请选择 dragAndDropBy(源元素, xOffset 偏移量, yOffset 偏移量)。
  • 🚀 务必等待源元素和目标元素都存在后再调用拖拽操作,以避免测试不稳定。
  • 🎖️ 通过视觉验证或断言目标的属性变化来验证下拉,以便测试确认真正的交互,而不仅仅是排队的操作。
  • 🏆 AI 辅助定位器可在 UI 更新后修复损坏的 XPath,从而减少在 CI 管道中运行的拖放套件的维护工作。

拖放 Selenium

什么是拖放功能? Selenium?

拖放 Selenium 是一种自动化交互方式,它模拟点击并按住源元素,将其在页面上移动,然后将其释放到目标位置。它广泛用于测试依赖拖放界面的现代 Web 应用程序,例如文件上传器、看板和商店。ping 购物车和仪表盘构建器。

In Selenium WebDriver,拖放操作是通过以下方式执行的: 行动 该类提供了专门的方法,可以将鼠标手势串联起来,并将它们作为单个复合动作执行。

拖放 Selenium

Actions 类公开了两种用于拖放自动化的主要方法:

语法:

Actions act = new Actions(driver);
//for drag and drop directly on an element
act.dragAndDrop(Source, Destination).build().perform();

//for drag and drop with pixel offsets
act.dragAndDropBy(WebElement Source, int xOffset, int yOffset).build().perform();

在这里, dragAndDrop() 获取源和目标 WebElement,而 dragAndDropBy() 接受源元素和要移动它的 x/y 像素偏移量。

如何拖放 Selenium

以下三个场景演示了在以下平台上的实际拖放自动化操作: Guru99 演示页面 https://demo.guru99.com/test/drag_drop.html目标是移动 银行 将借方元素存入 账户 借方区域,以便将 5000 美元的金额正确记为借方交易。

场景 1:使用 dragAndDrop 方法进行拖放

在这种情况下,源元素(银行)被拖放到目标元素(账户借方)上,方法是: dragAndDrop(source, target) 该方法直接接受源 WebElement 和目标 WebElement。

拖放场景 1 设置

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate the source (BANK) element
        WebElement Source = driver.findElement(By.xpath("//*[@id='credit2']/a"));
        // Locate the target (Account debit side) element
        WebElement Dest = driver.findElement(By.xpath("//*[@id='bank']/li"));

        // Create the Actions instance
        Actions act = new Actions(driver);
        // Perform drag and drop
        act.dragAndDrop(Source, Dest).build().perform();
    }
}

脚本运行完毕后, 银行 瓷砖移入 账户 借记区,5000 美元金额登记为借记。

Eclipse 运行拖放脚本

演示页面上的视觉效果如下所示:

拖放输出动画

场景 2:使用 dragAndDropBy 方法进行拖放

dragAndDropBy(source, xOffset, yOffset) 该方法提供像素级精度。而不是丢弃ping 对于目标元素,它将源元素沿 X 轴和 Y 轴移动指定的像素数。

要确定偏移量,请将鼠标悬停在浏览器中的目标区域上,然后使用检查器标尺或屏幕坐标扩展程序等工具读取像素坐标。

识别 dragAndDropBy 的像素偏移量

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropByExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate the source (BANK) element
        WebElement Source = driver.findElement(By.xpath("//*[@id='credit2']/a"));

        // Create the Actions instance
        Actions act = new Actions(driver);
        // Drag the source by 400 pixels right and 0 pixels down
        act.dragAndDropBy(Source, 400, 0).build().perform();
    }
}

该脚本将 BANK 图块按提供的偏移量移动,并将其放置在账户借方,从而产生与场景 1 相同的财务结果。

场景 3:拖放并验证多个元素

此场景将多个拖放操作串联起来,并通过对目标进行最终金额的验证来确认结果。多个源元素(银行、销售、5000、500)被移动到各自的借方和贷方区域,脚本会确认总计与预期余额相符。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropMultiple {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate sources
        WebElement srcBank = driver.findElement(By.xpath("//*[@id='credit2']/a"));
        WebElement srcSales = driver.findElement(By.xpath("//*[@id='credit1']/a"));
        WebElement src5000 = driver.findElement(By.xpath("//*[@id='fourth']/a"));
        WebElement src500 = driver.findElement(By.xpath("//*[@id='fourth']/a"));

        // Locate targets
        WebElement debitSide = driver.findElement(By.xpath("//*[@id='bank']/li"));
        WebElement creditSide = driver.findElement(By.xpath("//*[@id='loan']/li"));
        WebElement amount7 = driver.findElement(By.xpath("//*[@id='amt7']/li"));
        WebElement amount8 = driver.findElement(By.xpath("//*[@id='amt8']/li"));

        Actions act = new Actions(driver);
        act.dragAndDrop(srcBank, debitSide).build().perform();
        act.dragAndDrop(srcSales, creditSide).build().perform();
        act.dragAndDrop(src5000, amount7).build().perform();
        act.dragAndDrop(src500, amount8).build().perform();

        // Verify the displayed total
        String total = driver.findElement(By.xpath("//*[@id='totamt']")).getText();
        if (total.equals("5500")) {
            System.out.println("Test Passed: total matches expected 5500");
        } else {
            System.out.println("Test Failed: actual total " + total);
        }
    }
}

此模式演示了如何将拖放与断言相结合,以验证功能行为,而不仅仅是视觉运动。

拖放自动化最佳实践

拖放式测试是所有脚本中最不稳定的一种。 Selenium 套件之所以不适用,是因为它们依赖于精确的鼠标坐标和 DOM 就绪状态。以下做法可确保它们的可靠性:

  • 等待元素: 绝大部分储备使用 WebDriverWait - ExpectedConditions.elementToBeClickable 在调用拖拽功能之前。
  • 优先选择拖放方式 Java脚本修改: 原生 HTML5 拖拽事件有时需要 Java脚本回退方案,但首先依赖 Actions API。
  • 将目标滚动到视野中: 屏幕外目标地址会导致静默失败。使用 Actions.scrollToElement 或者 Java拖动前先滚动脚本。
  • 核实结果: 删除操作后,始终要断言可衡量的状态变化(文本、属性、计数),而不是相信操作已运行。
  • 以稳定分辨率运行: 如果视口大小与用于计算偏移量的大小不同,像素偏移拖动将会失效。

常见问题

拖放 Selenium 是一种自动化的鼠标手势,用于拾取源元素并将其释放到目标元素上。它通过 Actions 类中的 dragAndDrop 或 dragAndDropBy 方法实现。

dragAndDrop 方法接受源 WebElement 和目标 WebElement。dragAndDropBy 方法接受源元素以及 x 和 y 像素偏移量,当目标元素不是离散元素时,可以实现更精确的控制。

`build()` 函数将链式交互编译成一个复合 Action,而 `perform()` 函数则执行该 Action。如果没有 `perform()` 函数,排队的步骤将永远不会在浏览器中运行。

许多 HTML5 网站使用原生拖拽事件,而 Actions API 并非总是能触发这些事件。在这种情况下,可以通过 executeScript 来分发 dragstart、dragover 和 drop 事件。 Java脚本回退。

打开浏览器开发者工具,将鼠标悬停在目标元素上,读取该元素的 getBoundingClientRect 值。trac从源位置到目标位置的偏移量,得到以像素为单位的 x 和 y 偏移量。

是的。将源和目标查找用 WebDriverWait 包裹起来,并设置 ExpectedConditions.elementToBeClickable,这样拖拽操作只有在两个元素都可交互后才会执行,从而减少 CI 运行中的不稳定情况。

AI 工具提供自愈定位器,可在 XPath 发生变化时自动调整,并为源元素和目标元素推荐稳定的选择器。这降低了跨版本运行的拖放式套件的维护成本。

是的。AI 编码助手可以将“将 BANK 拖到借方并确认总额”这样的简单英语场景转化为完整的操作链,包括拖放、构建、执行和验证步骤。

总结一下这篇文章: