Java - 拖放不在selenium 3.8上工作

时间:2018-03-20 18:03:45

标签: java selenium selenium-webdriver drag-and-drop

拖放不使用selenium 3.8。

Here is the JS code for the element

这是我尝试过的。但它只是选择元素。保持和放弃不会发生。

WebElement source = driver.findElement(By.xpath("//tbody[@class ='lt-body']//tr[@data-test-id='table-row-id-20']//td[contains(@id,'ember')]//div[contains(@id,'ember')]//*[name()='svg']//*[name()='ellipse']"));
WebElement destination = driver.findElement(By.xpath("//tbody[@class ='lt-body']//tr[@data-test-id='table-row-id-3']//td[contains(@id,'ember')]//div[contains(@id,'ember')]//*[name()='svg']//*[name()='ellipse']"));

Actions builder = new Actions(driver);
int x2 =destination.getLocation().getX();
int y2 = destination.getLocation().getY();
builder.clickAndHold(source);
builder.moveByOffset(x2,y2);
builder.moveToElement(destination);
builder.release();
builder.perform();

也试过这个。

builder.clickAndHold(source).moveByOffset(x2,y2).moveToElement(destination).release().build().perform();

也和机器人一起尝试过。每次我只能看到源和目标元素都被选中。但不要拖延。

还尝试了dragAndDrop of ActionsChain。那也没有用。

1 个答案:

答案 0 :(得分:1)

使用以下基于javascript的方法。这是非常简洁的拖放方式,只要给出两个元素。这几乎每次都有效。祝你好运。

public void dragAndDrop(WebElement from, WebElement to) {
        js.executeScript("function createEvent(typeOfEvent) {\n" + "var event =document.createEvent(\"CustomEvent\");\n"
                + "event.initCustomEvent(typeOfEvent,true, true, null);\n" + "event.dataTransfer = {\n" + "data: {},\n"
                + "setData: function (key, value) {\n" + "this.data[key] = value;\n" + "},\n"
                + "getData: function (key) {\n" + "return this.data[key];\n" + "}\n" + "};\n" + "return event;\n"
                + "}\n" + "\n" + "function dispatchEvent(element, event,transferData) {\n"
                + "if (transferData !== undefined) {\n" + "event.dataTransfer = transferData;\n" + "}\n"
                + "if (element.dispatchEvent) {\n" + "element.dispatchEvent(event);\n"
                + "} else if (element.fireEvent) {\n" + "element.fireEvent(\"on\" + event.type, event);\n" + "}\n"
                + "}\n" + "\n" + "function simulateHTML5DragAndDrop(element, destination) {\n"
                + "var dragStartEvent =createEvent('dragstart');\n" + "dispatchEvent(element, dragStartEvent);\n"
                + "var dropEvent = createEvent('drop');\n"
                + "dispatchEvent(destination, dropEvent,dragStartEvent.dataTransfer);\n"
                + "var dragEndEvent = createEvent('dragend');\n"
                + "dispatchEvent(element, dragEndEvent,dropEvent.dataTransfer);\n" + "}\n" + "\n"
                + "var source = arguments[0];\n" + "var destination = arguments[1];\n"
                + "simulateHTML5DragAndDrop(source,destination);", from, to);

    }