在方法中使用网络元素

Using webelements in a method

我目前找到了一些代码,应该允许我在参数中包含网络元素的代码中自动拖放。应该在这些参数中放置什么?我使用了以下内容:

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

None 这些对我有用,下面是我正在使用的代码的副本。

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);
}

}

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

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

dragAndDropElement(dragFrom,dragTo, 10);