我无法使用 Selenium 3.141.59 + java (1.8) 在 HTML5 元素上执行拖放操作。我也尝试过本组中提到的其他解决方案(通过 JavaScriptExecutor)。但没有任何解决方案有效。您能否帮我为我的问题提供具体的解决方案。
我正在使用 Selenium(3.141.59) + Java (1.8) + Cucumber Framework + Selenium Grid (4)
我已经遵循了讨论,但它是针对Python的,但我需要Java中的解决方案。
我对 selenium 4 也有同样的问题。我发现这个 javascript 对我有用。我找不到讨论的链接,但找到下面的代码片段:
WebElement From = driver.findElement(By.xpath(Source_locator));
WebElement To = driver.findElement(By.xpath(Target_locator));;
//HTML 5
final String java_script =
"var src=arguments[0],tgt=arguments[1];var dataTransfer={dropEffe" +
"ct:'',effectAllowed:'all',files:[],items:{},types:[],setData:fun" +
"ction(format,data){this.items[format]=data;this.types.append(for" +
"mat);},getData:function(format){return this.items[format];},clea" +
"rData:function(format){}};var emit=function(event,target){var ev" +
"t=document.createEvent('Event');evt.initEvent(event,true,false);" +
"evt.dataTransfer=dataTransfer;target.dispatchEvent(evt);};emit('" +
"dragstart',src);emit('dragenter',tgt);emit('dragover',tgt);emit(" +
"'drop',tgt);emit('dragend',src);";
((JavascriptExecutor)driver).executeScript(java_script, From, To);
要在网站中执行dragAndDrop()作为示例,您需要为elementToBeClickable()引入WebDriverWait,并且可以使用以下定位器策略:
使用XPATH:
driver.get("http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html")
WebElement drag = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[starts-with(@id, 'box') and text()='Rome']")));
WebElement drop = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[starts-with(@id, 'box') and text()='South Korea']")));
new Actions(driver).dragAndDrop(drag, drop).build().perform();
这对我有用:
string script = @"function simulateDragAndDrop(source, target) {
const dataTransfer = new DataTransfer();
function trigger(eventType, element) {
const event = new DragEvent(eventType, {
bubbles: true,
cancelable: true,
dataTransfer: dataTransfer,
});
element.dispatchEvent(event);
}
trigger('dragstart', source);
trigger('dragenter', target);
trigger('dragover', target);
trigger('drop', target);
trigger('dragend', source);
}
simulateDragAndDrop(arguments[0], arguments[1]);";
ExecuteJavaScript(script, source, destination);