htmlunit-driver - 如何模拟拖放?

htmlunit-driver - how to simulate drag-and-drop?

有没有办法用 htmlunit-driver 模拟拖放?

当使用 Actions 时它抛出一个 UnsupportedException

里面 class HtmlUnitMouse:

  @Override
  public void mouseMove(Coordinates where, long xOffset, long yOffset) {
    throw new UnsupportedOperationException("Moving to arbitrary X,Y coordinates not supported.");
  }

我尝试这样做的尝试:

第一次尝试

(new Actions(driver)).dragAndDropBy(sliderHandle, 50, 0)
                     .build()
                     .perform();

第二次尝试

(new Actions(driver)).moveToElement(sliderHandle)
                     .clickAndHold()
                     .moveToElement(sliderHandle, 50, 0)
                     .release()
                     .build()
                     .perform();

有解决办法吗?

HtmlUnitGUI-Less 浏览器,适用于 Java 程序 ,它可以为我们做很多事情,但不是全部。而且,正如您所注意到的,它不支持拖放等操作

new UnsupportedOperationException("Moving to arbitrary X,Y coordinates not supported.");

与其他 Selenium 驱动程序相反,例如 ,您的示例在其中应该可以正常工作。

但是,如果您仍然需要它来进行无头 Web 测试,则有一个选项 PhantomJS. Yes, it is focused for JS testing, but there is a great project called Ghost Driver(在 PhantomJS 的简单 JS 中实现 Webdriver Wire 协议)启用 Java 绑定连同硒 API。

使用步骤非常简单:

  1. Install PhantomJS in your OS 并将可执行文件正确添加到您的 PATH 环境变量中。
  2. 将 Maven 依赖项添加到您的 pom.xml(连同 Selenium 库:selenium-javaselenium-support):

    <dependency>
        <groupId>com.github.detro</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.2.0</version>
    </dependency>
    
  3. 并调整您的代码以使用它:

    // Set this property, in order to specify path that PhantomJS executable will use
    System.setProperty("phantomjs.binary.path", System.getenv("PHANTOM_JS") + "/bin/phantomjs.exe");
    
    // New PhantomJS driver from ghostdriver
    WebDriver driver = new PhantomJSDriver();
    driver.get("https://jqueryui.com/resources/demos/draggable/default.html");
    
    // Find draggable element
    WebElement draggable = driver.findElement(By.id("draggable"));
    
    System.out.println("x: " + draggable.getLocation().x 
            + ", y: " + draggable.getLocation().y);
    
    // Perform drag and drop
    (new Actions(driver)).dragAndDropBy(draggable, 50, 0)
        .build()
        .perform();
    
    System.out.println("x: " + draggable.getLocation().x 
            + ", y: " + draggable.getLocation().y);
    

最终输出:

x: 8, y: 8
x: 58, y: 8