如何使用 Selenium WebDriver 部分截图(帧)?
每当我们在测试过程中遇到故障时,一种常见的方式是在出现与预期结果偏差的位置拍摄屏幕截图。因此,将屏幕截图作为创建缺陷的附件被认为是一个必须的步骤。
在为大量测试用例执行自动化时,拍摄屏幕截图对于推断一个测试用例为何失败(对于开发和测试团队来说)至关重要。当他们对故障进行调试时,查阅屏幕截图并得出结论,故障是否是因为脚本问题还是应用程序的缺陷。
有时,我们可能需要捕获特定元素的屏幕截图。在这里,我们必须捕获整个页面的屏幕截图,然后再根据元素的位置和尺寸对图像进行裁剪。
示例
代码实施。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.Point;
import java.awt.image.BufferedImage;
public class ScrshtElemnt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url ="https://tutorialspoint.com/about/about_careers.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify logo
WebElement l=driver.findElement(By.xpath( "//*[@class='top-logo']"));
// capture screenshot and store the image
File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage f = ImageIO.read(s);
//location of webelement
Point location= l.getLocation();
// Dimension of element
int w= l.getSize().getWidth();
int h=l.getSize().getHeight();
// Image Crop
BufferedImage cImage= f.getSubimage(location.getX(), location.getY(), w, h);
ImageIO.write(cImage, "png", s);
FileUtils.copyFile(s, new File("tutorialspointlogo.png"));
driver.quit();
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP