在方法中使用webelements

时间:2015-02-07 17:53:20

标签: java testing selenium selenium-webdriver automation

我目前发现了一些代码,可以让我自动拖放代码中的web元素。应该在这些参数中放置什么?我使用了以下内容:

driver.findElements(By.linkText("Policy"));  
findElements(By.linkText("Policy"));                                         
By.linkText("Policy");

这些都不适用于我下面是我正在使用的代码的副本。

public void dragAndDropElement(WebElement dragFrom, WebElement dragTo, int xOffset) throws Exception {
    //Setup robot
    Robot robot = new Robot();
    robot.setAutoDelay(50);

    //Fullscreen page so selenium coordinates work
    robot.keyPress((InputEvent.BUTTON1_MASK));
    Thread.sleep(2000);



    //Get size of elements
    Dimension fromSize = dragFrom.getSize();
    Dimension toSize = dragTo.getSize();

    //Get centre distance
    int xCentreFrom = fromSize.width / 2;
    int yCentreFrom = fromSize.height / 2;
    int xCentreTo = toSize.width / 2;
    int yCentreTo = toSize.height / 2;
    //Get x and y of WebElement to drag to
    Point toLocation = dragTo.getLocation();
    Point fromLocation = dragFrom.getLocation();

    //Make Mouse coordinate centre of element
    toLocation.x += xOffset + xCentreTo;
    toLocation.y += yCentreTo;
    fromLocation.x += xCentreFrom;
    fromLocation.y += yCentreFrom;
    //Move mouse to drag from location
    robot.mouseMove(fromLocation.x, fromLocation.y);
    //Click and drag
    robot.mousePress(InputEvent.BUTTON1_MASK);
    //Drag events require more than one movement to register
    //Just appearing at destination doesn't work so move halfway first
    robot.mouseMove(((toLocation.x - fromLocation.x) / 2) + fromLocation.x, ((toLocation.y - fromLocation.y) / 2) + fromLocation.y);

    //Move to final position
    robot.mouseMove(toLocation.x, toLocation.y);
    //Drop
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
}

}

1 个答案:

答案 0 :(得分:0)

使用方法我创建了参数中所需的对象,希望这有帮助

WebElement dragFrom = driver.findELement(By.id("id"));
WebElement dragTo = driver.findELement(By.id("id"));

dragAndDropElement(dragFrom,dragTo, 10);