NoSuchElementException:没有这样的元素:无法定位 element:while 标识可拖放元素

NoSuchElementException: no such element: Unable to locate element:while identifying draggable and droppable element

我实际上是硒的新手。我正在尝试在演示网站上进行拖放操作:http://jqueryui.com/droppable/(这里转到演示-->Droppable)。

以下是我的 html 来源:

<div id="draggable" class="ui-widget-content ui-draggable ui-draggable-handle" style="position: relative;">
    <p>Drag me to my target</p>
</div>

以下是我的代码块:

WebElement drag=dr.findElement(By.xpath("//*[@id='draggable']"));
wait.until(ExpectedConditions.elementToBeClickable(drag));

WebElement drop=dr.findElement(By.xpath("//*[@id='droppable']"));

wait.until(ExpectedConditions.elementToBeClickable(drop));
//act.moveToElement(drop).build().perform();
act.dragAndDrop(drag, drop).build().perform();

问题是拖放元素位于 iframe 中。您需要使用 class='demo-frame'

切换到 iframe

切换到 iframe 后,您就可以找到您的元素并与之交互。

拖动的元素和拖放的元素在<iframe>内。所以你必须先切换到预期的 frame 然后找到 draggabledroppable 元素并执行 dragAndDrop()如下:

这是完整的代码片段:

System.setProperty("webdriver.gecko.driver", "C:\path\to\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://jqueryui.com/droppable/");
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@class='demo-frame']")));
WebElement  from = driver.findElement(By.id("draggable"));
WebElement  to = driver.findElement(By.id("droppable"));
new Actions(driver).dragAndDrop(from, to).build().perform();
System.out.println("Drag and Drop Completed");
driver.quit();