在selenium java中拖放

时间:2017-02-13 07:22:03

标签: java selenium

我尝试将内容拖放到selenium中的搜索文本框中,但它执行拖动操作但不会将其拖放到search-textbox中。所以我的问题是如何放入文本框。

driver.get("http://stackoverflow.com/questions/42159265/drag-and-drop-content-into-textbox-by-using-selenium");                 
WebElement from = driver.findElement(By.xpath("//*[@id='qinfo']/tbody/tr[1]/td[2]/p/b"));
Actions builder = new Actions(driver);
        builder.doubleClick(from).perform();
        Thread.sleep(1000);

WebElement to = driver.findElement(By.name("q"));
Action dragAndDrop = builder.clickAndHold(from).moveToElement(to).release(to).build();
        dragAndDrop.perform();

3 个答案:

答案 0 :(得分:1)

所以这件事让我疯狂了几天,但我找到了答案。

制作了一个关于它的视频

https://www.youtube.com/watch?v=hOprGzKBD9I&feature=youtu.be

用文字/代码解释需要做什么

1 - 你需要导入一个外部 JS 文件 resources/drag_and_drop.js 2 - 在你需要运行 make 一个将执行 JS 的函数之后

下面是我的 -

  • 此方法使用 selenium webdriver 实现拖放操作

  • 字符串必须是 CSS Locations

      public void dragIT (String Fromlocator, String ToLocator) 
    
    
    
      String filePath = "resources/drag_and_drop.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();
      String commandToExecute =  "$('"+Fromlocator+"').simulateDragDrop({ dropTarget: '"+ToLocator+"'});";
    
      javaScript = javaScript + commandToExecute;
      ((JavascriptExecutor)driver).executeScript(javaScript)   }
    

答案 1 :(得分:0)

您可以尝试:

Actions dragAndDrop= new Actions(driver);
dragAndDrop.clickAndHold(DragFrom).moveToElement(DragTo).release().build().perform();

答案 2 :(得分:0)

第一个WebDriver / Selenium DragAndDrop似乎不再起作用,最好是在工作和不工作之间,具体取决于驱动程序,浏览器和selenium的发布。我没有发现任何java解决方法确实有效。

clickAndHold() moveToElement() release()  // solutions don't work

在查看下面提到的网站后,我将一个有效的Java示例放在一起。我的解决方案是使用rcorreia的javascript

Elemental Selenium Drag N Drop - 用于测试Drag N Drop的示例应用 rcorreia/drag_and_drop_helper.js - rcorreia的javascript帮助代码

RomanIsko/elemental-selenium-tips - csharp实现

我想通过查看romanisko csharp代码来了解如何集成javascript文件。

JSDriver.ExecuteScript(dnd_javascript + "$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});");

从上面我提出了以下Java解决方案:

DragAndDropJsHelper.java

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 {
        // the javascript file must be read into a single string no line breaks
        try (BufferedReader br = Files.newBufferedReader(Paths.get(getURIFromURL(jsFile)))) {
            dragndrop_js = br
                    .lines()
                    .collect(Collectors.joining(" "));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    // helper method, I'm using maven my js file is in src/test/resources
    @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);
    }

}

我的DragAndDropTest.java的一部分

@Test
public void dragAtoBTest() {
    try {
        WebElement weA = driver.findElement(DragNDropPage.COLUMN_A);
        WebElement weB = driver.findElement(DragNDropPage.COLUMN_B);
        DragAndDropJsHelper ddh = new DragAndDropJsHelper("drag_and_drop_helper.js");

        ddh.dragDrop(driver, "#column-a", "#column-b");

        log.info("wait for opacity to change 1, indicating move complete");
        wait.until(ExpectedConditions.attributeToBe(weA, "opacity", "1"));
        assertThat(weA.findElement(page.columnHeader).getText(), containsString("B"));

    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        Assert.fail("FAILED validLoginTest");
    }
}

注意:使用drag_and_drop.js需要src和dst为css选择器字符串,我不知道xpath是否可行。如果更好的话会更好 它将处理输入参数的WebElement和/或BY。不幸的是,我的javascript不足以进行修改。

另见:

Selenium Actions drag and drop not working on chrome browser

Drag and drop support for an object via Gwen DSL