How to download an image using Selenium (any version)?

前端 未结 13 1590
夕颜
夕颜 2020-11-29 04:11

I was wondering, how can one use selenium/webdriver to download an image for a page. Assuming that the user session is required to download the image hence having pure URL i

13条回答
  •  醉酒成梦
    2020-11-29 04:29

    If you need to test that image is available and exists, you may do like this:

    protected boolean isResourceAvailableByUrl(String resourceUrl) {
        // backup current url, to come back to it in future
        String currentUrl = webDriver.getCurrentUrl();
        try {
            // try to get image by url
            webDriver.get(resourceUrl);
            // if "resource not found" message was not appeared - image exists
            return webDriver.findElements(RESOURCE_NOT_FOUND).isEmpty();
        } finally {
            // back to page
            webDriver.get(currentUrl);
        }
    }
    

    But you need to be sure, that going through currentUrl will really turn you back on page before execution of this method. In my case it was so. If not - you may try to use:

    webDriver.navigate().back()
    

    And also, unfortunately, as it seems, there is no any chance to analyze response status code. That's why you need to find any specific web element on NOT_FOUND page and check that it was appeared and decide then - that image doesn't exist.

    It is just workaround, cause I found no any official way to solve it.

    NOTE: This solution is helpful in case when you use authorized session to get resource, and can't just download it by ImageIO or strictly by HttpClient.

提交回复
热议问题