问题
Enter image description here I have the following code for drag and drop an item from one location to another location
By sourceLocatorDragAndDrop = By.cssSelector("#available_objects_parent tbody tr td:eq(4)");
By destinationLocatorDragAndDrop = By.cssSelector("#assigned_objects_parent table tbody");
Actions action = new Actions(webDriver);
action.dragAndDrop(webDriver.findElement(sourceLocatorDragAndDrop) ,webDriver.findElement(destinationLocatorDragAndDrop)).build().perform();
This code gives the following error:
org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified (Session info: chrome=74.0.3729.131) (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Can anyone tell how to fix this issue?
回答1:
You can use JavaScript also:-
Because in HTML5 Action draganddrop function is not working,I use javascript and its working fine for me:-
WebElement From = driver.findElement(By.id("sourceImage"));
WebElement To = driver.findElement(By.id("targetDiv"));
//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);
And using Actions the code is below:-
WebElement From = driver.findElement(By.id("sourceImage"));
WebElement To = driver.findElement(By.id("targetDiv"));
Actions builder = new Actions(driver);
Action dragAnddrop = builder.clickAndHold(From)
.moveToElement(To)
.release(To)
.build();
dragAnddrop.perform();
Use firefox IDE for finding xpath. For more information go through this link.
回答2:
It seems you are using wrong cssSelector. You always can validate xpath in chrome developer options. Please go through below link. Please provide html code for the sourceLocatorDragAndDrop and destinationLocatorDragAndDrop so that we can understand what went wrong.
https://yizeng.me/2014/03/23/evaluate-and-validate-xpath-css-selectors-in-chrome-developer-tools/
回答3:
:eq() is a JQuery selector, not cssselector. Selenium doesn't recognize it. The closest match is :nth-child()
By sourceLocatorDragAndDrop = By.cssSelector("#available_objects_parent tbody tr td:nth-child(4)");
来源:https://stackoverflow.com/questions/56141490/drag-and-drop-not-working-with-chrome-webdriver-in-java