供参考的是有关 Actions 的文档。
我认为你在你的行动中遗漏了一些步骤:
WebElement ele = driver.findElement(By.id("btn1"));
Actions builder = new Actions(driver);
builder.clickAndHold(ele);
// Any other actions you want to build onto this
// eg. builder.moveToElement(ele)
// .release(ele)
// .etc...
// Now build and get the Action
Action action = builder.build();
// Perform the action(s)
action.perform();
// Take your screenshot
// Build the release action
builder = new Actions(driver);
builder.release(ele);
// Get the built action and perform
action = builder.build();
action.perform();
这会变得复杂而令人厌烦。您可能需要考虑创建一个扩展 Actions 的新类,该类添加一个您可以调用的截屏方法,然后您的代码可以简化为:
WebElement elm = driver.findElement(By.id("btn1"));
Actions builder = new Actions(driver);
builder.clickAndHold(elm).takeScreenshot().release(elm);
builder.build().perform();
我没有编译器或 IDE 来测试它,但它应该可以工作。
以下是最终适用于 OP 的方法:
WebElement elm = driver.findElement(By.id("btn1"));
Actions builder = new Actions(driver);
Action act = builder.clickAndHold(elm).build();
act.perform();
try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\Img\\screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
act = builder.release(elm).build();
act.perform();