Reducing screenshot taking time on selenium

1.4k views Asked by At

Taking screenshot is very fast if the code is executed on a server at localhost, less than a second (around 400-500ms):

private RemoteWebDriver driver;
private DesiredCapabilities dc = new DesiredCapabilities();

@Before
public void setUp() throws MalformedURLException {
    ....
    ....
    dc.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
    driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dc);
}

@Test
public void test() throws InterruptedException, IOException {
    driver.get("https://google.com");
    driver.findElement(By.name("q")).sendKeys("automation test");
    
    long before = System.currentTimeMillis();
    //here is the problem
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    long after = System.currentTimeMillis();
    System.out.println(after-before);

    FileUtils.copyFile(srcFile, new File("/Users/name/localpath/test.png"));
}

But if the target server is changed to public ip which has Selenium server installed, taking the screenshot will be slower (around 5 seconds). Maybe this could be due to the distance between the client and the server, so there must be a difference.

Is possible to reduce the screenshot taking time? I'm thinking about reducing the image resolution, but how do I adjust it?

2

There are 2 answers

2
Mate Mrše On

Crop the screenshot

One way of getting smaller sized screenshots (other than using various file formats) is changing the size of the screenshot: you can take a screenshot of a web element (or a region of a page) that is of special interest to you.

Try the following (you will need to use the BufferedImage class):

@Test
public void test() throws InterruptedException, IOException {
    driver.get("https://google.com");
    driver.findElement(By.name("q")).sendKeys("automation test");
    
    long before = System.currentTimeMillis();
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

    Point p = element.getLocation();
    int width = element.getSize().getWidth();  
    int height = element.getSize().getHeight();
    BufferedImage img = ImageIO.read(scrFile);
    BufferedImage elementScreenshot = img.getSubimage(p.getX(), p.getY(), width, height);
    //NOTE: the line above will crop the full page screenshot to element dimensions, change width and height if you wish to crop to region
    Image.write(elementScreenshot, "png", scrFile);

    FileUtils.copyFile(srcFile, new File("/Users/name/localpath/test.png"));
    long after = System.currentTimeMillis();
    System.out.println(after-before);
}
2
DMart On

The problem is transferring the file over the wire most likely. IT might also be in the creation of the file.

I would suggest trying with the Base64 output to see if that reduces the transfer time:

String screenshotAsBase64String = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);