【发布时间】:2018-06-14 07:12:42
【问题描述】:
能否请您帮助我使用 selenium 和 java 自动拖放。
http://akserg.github.io/ng2-webpack-demo/#/dnd
我们在项目中使用的类似示例,但没有发生拖放,我们尝试了不同的方法来找到解决方案,但没有用。
如果你们中的任何人对此有解决方案,请回复,我们将不胜感激。
请找代码
public class ND2DND
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new ChromeDriver();
driver.get("http://akserg.github.io/ng2-webpack-demo/#/dnd");
driver.manage().window().maximize();
Thread.sleep(2000);
WebElement sourceElement = driver
.findElement(By.xpath("/html/body/app-root/demo-dnd/div/div/simple-dnd/div/div[1]/div/div[2]/div/div/div"));
System.out.println(sourceElement.getText());
// Element on which need to drop.
WebElement destinationElement = driver
.findElement(By.xpath("/html/body/app-root/demo-dnd/div/div/simple-dnd/div/div[2]/div/div[2]"));
try
{
if (sourceElement.isDisplayed() && destinationElement.isDisplayed())
{
try
{
Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(sourceElement));
Action atc2 = actions.clickAndHold(sourceElement).moveToElement(destinationElement).release(destinationElement).build();
atc2.perform();
Thread.sleep(1000);
System.out.println("dropped");
}
catch (StaleElementReferenceException e)
{
System.out.println("Element stale is continuing");
}
}
}
catch (Exception e)
{
System.out.println("Unable to drag and drop " + e);
}
}
}
提前致谢。
上述网址的解决方法:
wait.until(ExpectedConditions.elementToBeClickable(sourceElement));
String basePath = new File("").getAbsolutePath();
final String JQUERY_LOAD_SCRIPT = (basePath + "/lib/jquery_load_helper.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
//http://stackoverflow.com/questions/29381233/how-to-simulate-html5-drag-and-drop-in-selenium-webdriver
//"where jquery_load_helper.js contains:"
String filePath = basePath + "/lib/drag_and_drop_helper.js";
//JQuery can ONLY work with id and css , xpath does NOT work with it.
//String source = "//section[@id='wrapper']/article/ul/li[4]/a";
String source = ".panel-success > div:nth-child(2) > ul:nth-child(1)";
String target = "div.panel-info:nth-child(1) > div:nth-child(2)";
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 + "window.jQuery('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
【问题讨论】:
-
我尝试了几种方法,也无法让它工作。我想知道拖放是否坏了。你试过不同的浏览器吗?
-
顺便说一句,您可以使用实际的
Actions.dragAndDrop()method。它不适合我,但代码更简单。 -
感谢杰夫调查。最后我得到了解决方案,希望它会对你有所帮助。请在上面找到解决方案。