如何在 Selenium 中执行拖放操作?
software testingautomation testingselenium web driver更新于 2026/2/10 14:22:17
我们可以借助 Actions 类在 Selenium 中执行拖放操作。为了执行拖放操作,我们将使用 dragAndDrop (source, target) 方法。最后使用 build().perform() 执行所有步骤。
示例
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.Action;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DrgAndDrp{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = " https://jqueryui.com/draggable/v";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
driver.switchTo().frame(0);
WebElement source= driver.findElement(By.id("draggable"));
WebElement target= driver.findElement(By.id("droppable"));
// dragAndDrop() 方法将元素从源拖到目标
Actions a = new Actions(driver);
Thread.sleep(5000);
a.dragAndDrop(source, target).build().perform();
Thread.sleep(5000);
driver.quit();
}
}

