Search code examples
javahtmlimagehtmlunit

Java/HtmlUnit - How to get an HtmlImage from an HtmlImageInput?


I've got an image on an html page that is also an input.

<input type="image" src=...

I couldn't care less about clicking the image. I want to save the image to a File. It seems to be impossible which seems ridiculous. I tried casting from HtmlImageInput to HtmlImage but I just get an error. How can I do this? Do I need to switch from HtmlUnit to something else? I don't care what I need to do to get this done.

By the way, I tried using selenium and taking a screenshot but it's taking a screenshot of the wrong area. Tried multiple different xpaths to the same element and it always takes the wrong screenshot.


Solution

  • Thanks for reporting.

    Similar to HtmlImage, .saveAs(File) has been just added to HtmlImageInput.

    BTW, if you can't use latest snapshot, then you can use:

    try (WebClient webClient = new WebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8080");
        HtmlImageInput input = page.querySelector("input");
        URL url = page.getFullyQualifiedUrl(input.getSrcAttribute());
        final String accept = webClient.getBrowserVersion().getImgAcceptHeader();
        final WebRequest request = new WebRequest(url, accept);
        request.setAdditionalHeader("Referer", page.getUrl().toExternalForm());
        WebResponse imageWebResponse =  webClient.loadWebResponse(request);
    }