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

前端 未结 13 1451
夕颜
夕颜 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:53

    Although @aboy021 JS code is syntactly correct I couldn't the code running. (using Chrome V83.xx)

    However this code worked (Java):

        String url = "/your-url-goes.here.jpg";
        String imageData = (String) ((JavascriptExecutor) driver).executeAsyncScript(
                "var callback = arguments[0];" + // The callback from ExecuteAsyncScript
                        "var reader;" +
                        "var xhr = new XMLHttpRequest();" +
                        "xhr.onreadystatechange = function() {" +
                        "  if (xhr.readyState == 4) {" +
                            "var reader = new FileReader();" +
                            "reader.readAsDataURL(xhr.response);" +
                            "reader.onloadend = function() {" +
                            "    callback(reader.result);" +
                            "}" +
                        "  }" +
                        "};" +
                        "xhr.open('GET', '" + url + "', true);" +
                        "xhr.responseType = 'blob';" +
                        "xhr.send();");
    
        String base64Data = imageData.split(",")[1];
    
        byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
        try (OutputStream stream = new FileOutputStream("c:\\dev\\tmp\\output.jpg")) {
            stream.write(decodedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
提交回复
热议问题