Is it possible to capture a screen shot for a webelement directly by using WebDriver?

前端 未结 4 913
执笔经年
执笔经年 2021-01-13 07:46

At Interface TakesScreenshot page I found this:

Capture the screenshot and store it in the specified location. For WebDriver extending TakesScreens

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 08:28

    Try this

    WebDriver driver = new FirefoxDriver();
    WebElement webElement = driver.findElements(By.xpath("//html")).get(0);
    
    File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    BufferedImage img = ImageIO.read(screen);
    
    File f = new File('element.png');
    
    Point p = webElement.getLocation();
    int width = webElement.getSize().getWidth();
    int height = webElement.getSize().getHeight();
    BufferedImage dest = img.getSubimage(p.getX(), p.getY(), width, height);
    ImageIO.write(dest, "png", f);
    

    Then, after you verify this works, replace the webElement with your own element. Run this code first just to make sure your webdriver has the screen shot capability and that your file io works as expected (ie you will discover where the files are saved).

    What this does is capture a screenshot, saves it to file. Then, reads that file as an image and grabs a subimage based on the position of the element. Then, it saves that sub image to file. This requires two file writes and a file read (so there would probably be a good optimization for this).

提交回复
热议问题