我想使用selenium在W3school网页中执行拖放操作。代码工作正常但输出没有显示在网页上。
链接是: - http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop
我的代码是: -
public String dragAndDrop(String object,String data){
APP_LOGS.debug("waiting for popup closer");
try{
driver.switchTo().frame("iframeResult");
WebElement element = driver.findElement(By.xpath(".//*[@id='drag1']"));
WebElement target = driver.findElement(By.xpath(".//*[@id='div1']"));
(new Actions(driver)).dragAndDrop(element, target).build().perform();
}catch(Exception e){
return Constants.KEYWORD_FAIL+" -- Unable to drag"+e.getMessage();
}
return Constants.KEYWORD_PASS;
}
答案 0 :(得分:1)
我们还可以使用Selenium中的Actions类和robot类与键盘/鼠标事件进行交互。我使用Robot
课来解决您的问题。
Robot
类中包含java.awt
类。您可以查看the docs中的所有方法。
public static void Task1() throws AWTError, AWTException, InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop");
driver.switchTo().frame("iframeResult");
WebElement element1 = driver.findElement(By.xpath(".//img[@id='drag1']"));
WebElement element2 = driver.findElement(By.xpath(".//*[@id='div1']"));
Actions action = new Actions(driver);
Point element3 = driver.findElement(By.xpath(".//*[@id='drag1']")).getLocation();
int i=element3.getX()+800;
int b=element3.getY()+250;
Robot robot = new Robot();
robot.mouseMove(i, b);
// Press left click of mouse
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.delay(4000);
robot.mouseMove(i+20, b-120);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(10000);
driver.close();
}