【问题标题】:Capture specific content in a page as an image file [duplicate]将页面中的特定内容捕获为图像文件[重复]
【发布时间】:2020-06-13 01:21:56
【问题描述】:

我的问题是如何将网页中的特定内容捕获到屏幕截图中,但我做不到。让我们考虑任何网页,如果我试图捕获任何一个类的内容并想在 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 welem = ...; -> File scrFile = welem.getScreenshotAs(OutputType.FILE); 并使用Apache Common IO 中的FileUtils 保存文件。
  • 我可以截取整个网页的截图,但我只想截取特定内容。这就是我卡住的地方
  • 阅读我的回答,如果有帮助,请告诉我。

标签: java selenium screenshot


【解决方案1】:

您需要获取要捕获的 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多