我的问题是如何将网页中的特定内容捕获到屏幕截图中,但我做不到。让我们考虑任何网页,如果我试图捕获任何一个类的内容,并且想要在 Selenium 中截取该类的屏幕截图,我该怎么做!我需要考虑尺寸吗?如果需要,我该怎么做?请告诉我如何做到这一点。
我在 selenium 中使用以下函数:
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullimg = ImageIO.read(screenshot);
Point point = element.getLocation();
int elewidth = element.getSize().getWidth();
int eleheight = element.getSize().getHeight();
BufferedImage elementScreenshot = fullimg.getSubimage(point.getX(), point.getY(),elewidth,
eleheight);
ImageIO.write(elementScreenshot, "png", new File("Path"));
第二个函数:
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, "png", new File("Path"));
最佳答案
您需要获取要捕获的 WebElement,并使用 Apache 的 FileUtils 将其保存为文件。
Apache 通用 IO:https://mvnrepository.com/artifact/commons-io/commons-io/2.7
WebDriver driver = ...;
try{
driver.get("https://www.google.com/");
WebElement logo = new WebDriverWait(driver, 60).until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[@id = 'main']")
)
);
File logoFile = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(logoFile, new File("logo.jpg"));
}catch(Exception e){
e.printStackTrace();
}finally{
driver.quit();
}
关于java - 将页面中的特定内容捕获为图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62348962/