我正在尝试使用java脚本解决方案,以便在IE11和Chrome上使用带java的selenium驱动程序进行拖放。我在Java1.8中使用selenium 3.4
这是我的代码:
**Web Element Initialisation**
@FindBy(how = How.CSS, css =".work-card-description.searchable-field")
private WebElement weDragFrom;
@FindBy(how = How.CSS,css = "div.resource-schedule.resource-ui-droppable div.hour-line:nth-of-type(11)")
private WebElement weDragTo;
**CODE**
protected void dragAndDrop( WebElement from, WebElement to)throws IOException,InterruptedException {
String basePath = new File("").getAbsolutePath();
String jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js";
final String JQUERY_LOAD_SCRIPT =(basePath + "/src/test/resources/jquery_load_helper.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(jQueryLoader,jquery_url);
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
String filePath =(basePath + "/src/test/resources/drag_and_drop_helper.js");
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine()) != null) {
buffer.append(line);
}
String javaScript = buffer.toString();
javaScript = javaScript + "$('"+from+"').simulateDragDrop({ dropTarget: '"+to+"'});";
((JavascriptExecutor)driver).executeScript(javaScript);
Thread.sleep(1000);
}误差
org.openqa.selenium.JavascriptException:错误:语法错误,无法识别的表达式:[FirefoxDriver: firefox (a57f702c-e519-4a71-98f8-015da1fba 509) -> css选择器:.work-card-description.searchable-field]构建信息:版本:'3.4.0',修订:‘未知’,时间:‘未知’系统信息:主机:驱动程序信息: org.openqa.selenium.firefox.FirefoxDriver rotatable=false,timeouts={implicit=0.0,pageLoad=300000.0,script=30000.0},pageLoadStrategy=normal,platform=ANY,specificationLevel=0.0,moz:accessibilityChecks=false,acceptInsecureCerts=true,browserVersion=55.0.3,platformVersion=6.3,moz:processID=6420.0,browserName=firefox,javascriptEnabled=true会话ID: a57f702c-e519-4a71-98f8-015da1fba 509( sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native方法)在sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62),sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45),java.lang.reflect.Constructor.newInstance(Constructor.java:423),org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:150),org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:115) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:45) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637) at org.openqa.selenium.remote.RemoteWebDriverPageObject.OptimiseSchedulePage.dragAndDrop(OptimiseSchedulePage.java:180) at PageObject.OptimiseSchedulePage.dragDropJobIntoDiary(OptimiseSchedulePage.java:120) at WebAdmin.FunctionalityTest.DragAndDrop(FunctionalityTest.java:71) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method,sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(方法)org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108) at org.testng.internal.Invoker.invokeMethod(Invoker.java:661) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)在org.testng.TestRunner.privateRun(TestRunner.java:744) at org.testng.TestRunner.run(TestRunner.java:602) at org.testng.SuiteRunner.runTest(SuiteRunner.java:380) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) at org.testng.SuiteRunner.run(SuiteRunner.java:289) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)在org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301) at org.testng.TestNG.runSuitesLocally(TestNG.java:1226) at org.testng.TestNG.runSuites(TestNG.java:1144) org.testng.TestNG.run(TestNG.java:1115) at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
请帮助我,我已经尝试了所有的解决办法,在这两个浏览器上,Action类根本不适合我。
在internet上的其他一些解决方法只是在没有任何错误的情况下执行,并且什么也不做。
根据我在阅读许多文章中的知识,我认为使用java(drag_and_drop_helper.js)肯定会奏效,我知道有些地方遗漏了一些东西。
**JAVASCRIPT(Drag_and_drop_helper)**
(function( $ ) {
$.fn.simulateDragDrop = function(options) {
return this.each(function() {
new $.simulateDragDrop(this, options);
});
};
$.simulateDragDrop = function(elem, options) {
this.options = options;
this.simulateEvent(elem, options);
};
$.extend($.simulateDragDrop.prototype, {
simulateEvent: function(elem, options) {
/*Simulating drag start*/
var type = 'dragstart';
var event = this.createEvent(type);
this.dispatchEvent(elem, type, event);
/*Simulating drop*/
type = 'drop';
var dropEvent = this.createEvent(type, {});
dropEvent.dataTransfer = event.dataTransfer;
this.dispatchEvent($(options.dropTarget)[0], type, dropEvent);
/*Simulating drag end*/
type = 'dragend';
var dragEndEvent = this.createEvent(type, {});
dragEndEvent.dataTransfer = event.dataTransfer;
this.dispatchEvent(elem, type, dragEndEvent);
},
createEvent: function(type) {
var event = document.createEvent("CustomEvent");
event.initCustomEvent(type, true, true, null);
event.dataTransfer = {
data: {
},
setData: function(type, val){
this.data[type] = val;
},
getData: function(type){
return this.data[type];
}
};
return event;
},
dispatchEvent: function(elem, type, event) {
if(elem.dispatchEvent) {
elem.dispatchEvent(event);
}else if( elem.fireEvent ) {
elem.fireEvent("on"+type, event);
}
}
});
})(jQuery);发布于 2018-05-24 01:49:53
我的解决方案看起来和你的非常相似。但是,下面的解决方案适用于我,请参阅:拖放硒-java
注意:您正在将src/dst ( to /from)的WebElement传递给js。我使用css选择器字符串,例如“#列-a”,“#列-b”id(s)。我对javascript不太了解,无法验证您是否可以使用WebElement。我猜这是你的问题。
我假设您也在使用helper.js -rcorreia的javascript助手代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class DragAndDropJsHelper {
Logger log = LogManager.getLogger(DragAndDropJsHelper.class.getName());
String dragndrop_js = null;
public DragAndDropJsHelper(String jsFile) throws IOException {
try (BufferedReader br = Files.newBufferedReader(Paths.get(getURIFromURL(jsFile)))) {
dragndrop_js = br
.lines()
.collect(Collectors.joining(" "));
} catch (IOException e) {
log.error(e.getMessage());
}
}
@SuppressWarnings("finally")
private URI getURIFromURL(String fileName) {
URI uri = null;
try {
URL url = this.getClass().getClassLoader().getResource(fileName);
uri = url.toURI();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
return uri;
}
}
/**
* Solution from elemental-selenium-tips
* https://github.com/tourdedave/elemental-selenium-tips/blob/master/39-drag-and-drop/csharp/DragAndDrop.cs
* JSDriver.ExecuteScript(dnd_javascript + "$('#column-a').simulateDragDrop({
* dropTarget: '#column-b'});");
*
* NOTE: Seems fragile, not sure if this works for XPATH or other src/dst type strings
* TODO: would be good if it worked with WebElement, or BY
*
* @param driver
* @param src
* - css string for source element
* @param dst
* - css string for destination element
*/
public void dragDrop(WebDriver driver, String src, String dst) {
String js = String.format("$('%s').simulateDragDrop({ dropTarget: '%s'});",src,dst);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript(dragndrop_js + js);
}
}https://stackoverflow.com/questions/46155527
复制相似问题