单击并按住Web元素时截取屏幕截图

时间:2013-05-23 17:45:17

标签: java selenium selenium-webdriver

我有一个带有焦点外观的网页元素,仅在点击并按住时显示。如何在发布之前点击元素并保持并捕获屏幕截图? 我到目前为止尝试的代码是:

Actions act = new Actions(driver);
WebElement ele = driver.findElement(By.id("btn1"));     
act.clickAndHold(ele);
<capture screenshot>
act.release(ele);

这确实采用了屏幕截图,但上面的代码clickAndHold并没有按住该元素。我怎么做?

2 个答案:

答案 0 :(得分:0)

您可以采用这种方式进行屏幕捕捉

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\career.jpg"));

答案 1 :(得分:0)

供参考here is the documentation on 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();