如果在应用程序中有两个可拖动元素,如何拖动?

时间:2016-05-16 21:23:21

标签: java eclipse selenium-webdriver draggable

我是selenium(Java)的新手。在练习的过程中,我发现这个页面中的两个元素都是可拖动的。我几乎一路试过...... http://the-internet.herokuapp.com/drag_and_drop

// ****Case 1****

    Actions builder = new Actions(driver);
    builder.dragAndDrop(fromWebElement, toWebElement);

// ****Case 2****

    Actions builder = new Actions(driver);
    Action dragAndDrop =
      builder.clickAndHold(fromWebElement).moveToElement(toWebElement)
        .release(toWebElement).build();
    dragAndDrop.perform();

// ****Case 3****
 Actions builder = new Actions(driver);
    Action dragAndDrop =
      builder.clickAndHold(fromWebElement).moveToElement(toWebElement, 2, 2)
        .release(toWebElement).build();
    dragAndDrop.perform();


 //****Case 4****
    Actions builder = new Actions(driver);
    builder.clickAndHold(fromWebElement).moveToElement(toWebElement).perform();
    Thread.sleep(2000);// add 2 sec wait
    builder.release(toWebElement).build().perform();


 //****Case 5****
    Point coordinates1 = fromWebElement.getLocation();
    Point coordinates2 = toWebElement.getLocation();
        Robot robot = new Robot();
        robot.mouseMove(coordinates1.getX(), coordinates1.getY());
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseMove(coordinates2.getX(), coordinates2.getY());
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        Thread.sleep(2000);

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

@Test
public void test() throws InterruptedException, AWTException{

    WebDriver driver = new FirefoxDriver();    

    driver.manage().window().maximize();
    driver.get("http://the-internet.herokuapp.com/drag_and_drop");
    Thread.sleep(3000);

    WebElement fromWebElement = driver.findElement(By.cssSelector("#column-a"));
    WebElement toWebElement = driver.findElement(By.cssSelector("#column-b"));

    int x = toWebElement.getLocation().getX();
    int y = toWebElement.getLocation().getY();

    Point coordinates = driver.findElement(By.cssSelector("#column-a")).getLocation();

     Robot robot = new Robot();
     robot.mouseMove(coordinates.getX()+120,coordinates.getY()+120);
     Thread.sleep(1000);

    Actions builder1 = new Actions(driver);
    builder1.clickAndHold(fromWebElement).moveToElement(toWebElement).release().build().perform();
    Thread.sleep(1000);
    Point coordinates1 = driver.findElement(By.cssSelector("#column-b")).getLocation();
    Robot robot1 = new Robot();
    robot1.mouseMove(coordinates1.getX()+120,coordinates1.getY()+120);


    Thread.sleep(1000);
    Robot bot = new Robot();
    bot.mouseMove(x +120, y+120);    
    bot.mousePress(InputEvent.BUTTON1_MASK);
    bot.mouseRelease(InputEvent.BUTTON1_MASK);
}

希望这会对你有所帮助。