为了实现Selenium测试的拖放,我提到了http://elementalselenium.com/tips/39-drag-and-drop提到使用javascript(来自https://gist.github.com/rcorreia/2362544)来处理拖放。
我按原样实现它并且它有效。但就我而言,我是源和目标元素的动态xpath。为了实现这一点,我尝试使用以下代码:
package org.test.selenium;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class HTML5DragAndDrop {
WebDriver driver = null;
@BeforeClass
public void setUp(){
System.out.println(System.getProperty("user.dir"));
String chromeDriver = System.getProperty("user.dir")+ File.separator + "drivers" + File.separator + "chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromeDriver);
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/drag_and_drop");
}
@AfterClass
public void tearDown(){
driver.quit();
}
@Test
public void testDragAndDrop() throws IOException, InterruptedException {
String filePath = "C://dnd.js";
String source = "//div[@id='column-a']";
String target = "//div[@id='column-b']";
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 + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
}
但它给出了错误:
org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected identifier
(会议信息:chrome = 35.0.1916.153)
但是,如果像下面这样使用source和target作为css,那么它的工作原理非常好:
String source = "#column-a";
String target = "#column-b";
有人可以建议我需要做的更改,以便上面的内容将与xpaths的源和目标元素一起使用吗?在我的情况下,我被限制使用xpath,而我只使用xpath执行此操作。
答案 0 :(得分:2)
你的问题是JQuery使用类似CSS的语法。在这种情况下,Xpath不会工作。
如果必须使用Xpath,则必须先将Xpath字符串转换为CSS,然后再将其附加到此JQuery字符串中:
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
如果您只使用Xpath来识别使用ID的div
,那么您可以在Java中尝试:
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcherSource = pattern.matcher(source);
Matcher matcherTarget = pattern.matcher(target);
String cssSource = "#" + matcherSource.group(1);
String cssTarget = "#" + matcherTarget.group(1);
javaScript = javaScript + "$('" + cssSource + "').simulateDragDrop({ dropTarget: '" + cssTarget + "'});";