我如何截取在 selenium 中失败的 webelement(部分屏幕而不是整个页面)的屏幕截图。我尝试使用 Point 来定位 webelement 的位置并 5aken 它工作的屏幕截图,但这是硬编码我想要一个运行时解决方案.例如,我的网页有 3 个字段、2 个文本框和 1 个按钮,由于第二个文本框,测试失败(任何失败,如元素未找到或元素被禁用)我只想在运行时截取第二个文本框的屏幕截图。请帮忙
最佳答案
您可以使用名为 aShot 的第三方库.它可以用于:
- 截取 WebElement 在不同平台(即 桌面浏览器、iOS 模拟器 Mobile Safari、Android 模拟器 浏览器)
- 捕获整页屏幕截图。
- 装饰截图
- 提供灵活的屏幕截图比较
将此依赖项添加到您的 pom.xml
:
<!-- https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot -->
<dependency>
<groupId>ru.yandex.qatools.ashot</groupId>
<artifactId>ashot</artifactId>
<version>1.5.3</version>
</dependency>
现在您可以通过以下方式截取屏幕截图:
public void takeScreenShotWhenFailed(WebDriver driver, WebElement webElement ){
Screenshot screenshot = new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, webElement);
ImageIO.write(screenshot.getImage(),"PNG",new File(System.getProperty("user.dir") +"\\Images\\googleLogo.png"));
}
更新:要检测程序失败的元素,您可以简单地用 try-catch
block 围绕每个步骤,然后在 catch
中您可以调用 screenshot
方法,例如:
WebElement element;
try{
element = driver.findElement(By.id("id"));
element.click();
}catch(Exception e){
takeScreenShotWhenFailed(driver,element);
}
关于java - 如何截取在 selenium 中失败的 webelement(部分屏幕而不是整个页面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56538474/