将页面中的特定内容捕获为图像文件[重复]

问题描述 投票:0回答:1

我的问题是如何将网页中的特定内容捕获到屏幕截图,但我不能。让我们考虑任何网页,如果我要捕获任何一个类的内容,并想在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"));
java selenium screenshot
1个回答
0
投票

您需要获取要捕获的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();
}
© www.soinside.com 2019 - 2024. All rights reserved.