无法使用javascript在Selenium WebDriver测试中执行HTML5拖放操作

Unable to perform HTML5 drag and drop using javascript for Selenium WebDriver test

本文关键字:测试 执行 HTML5 操作 拖放 WebDriver Selenium javascript      更新时间:2023-09-26

为了实现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

(Session info: chrome=35.0.1916.153)

但是,如果像下面这样使用source和target作为css,它工作得很好:

String source = "#column-a";
String target = "#column-b";

有人可以建议我需要做的更改,以便上面将工作与源和目标元素的xpath ?在我的例子中,我只能使用xpath我只能使用xpath

您的问题是JQuery使用类似css的语法。在这种情况下Xpath不起作用。

如果必须使用Xpath,则必须在将Xpath字符串附加到JQuery字符串之前将其转换为CSS:

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 + "'});";