Robot
Robot

Reputation: 101

Capture screenshot using htmlunitdriver?

How can I capture a screenshot using HtmlUnitDriver? I found that i can capture when I use FirefoxDriver but I don't want to use Firefox. So, please let me know how to capture images using HtmlUnitDriver.

I googled but none of the solutions I found are working for me. Please help!

Upvotes: 1

Views: 7788

Answers (2)

Supercreature
Supercreature

Reputation: 469

Flyingsaucer is a java library which lets you take screenshots of a webpage headlessly (without opening the page in a browser). The following code will capture a screenshot of the entire page resized into an image called "screenshot.png". The number 1024 specifies the width of the output screenshot. Find the libraries here http://mvnrepository.com/artifact/org.xhtmlrenderer

import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import org.xhtmlrenderer.simple.Graphics2DRenderer;

public class RenderPage {

    public static void main(String[] args) throws Exception {
        try {
             String address = "http://www.w3.org";
             BufferedImage buff = Graphics2DRenderer.renderToImageAutoSize(address, 1024);
             ImageIO.write(buff, "png", new File("screenshot.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

You can also use the method Graphics2DRenderer.renderToImage(address,1024,1024); to define your own size of screenshot.

You'll find that the screenshots look as if they were rendered on a phone. I don't know why this is, but I'm guessing that you can change Flyingsaucer's browser version somewhere to emulate the page on different browsers.

One more thing is that this code won't screenshot www.google.com but apparently this type of error can be solved by tidying up the page source with a library called JTidy.

Upvotes: 2

Storm
Storm

Reputation: 758

HtmlUnitDriver is GUI-less. see: here

Maybe you can use the following:

BufferedImage image = new Robot().createScreenCapture(newRectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("/screenshot.png"));

source

Upvotes: -1

Related Questions