简体   繁体   English

使用Javascript一次下载多个图像

[英]Download multiple images at once with Javascript

I'm attempting to download multiple images at once using javascript in a chrome extension.我正在尝试使用 chrome 扩展中的 javascript 一次下载多个图像。 I'd like to do this by firing clicks on each of the images (each wrapped in an href tag with a download attribute, and the class "clickit").我想通过点击每个图像(每个图像都包含在具有下载属性的 href 标签和类“clickit”中)来实现这一点。 The idea is to loop through each href with the clickit class and fire a mouse click, thus downloading the image.这个想法是使用 clickit 类遍历每个 href 并触发鼠标单击,从而下载图像。

The following code downloads only the first of n = 25 images, but is called 25 times (console logs "got here" that many times).以下代码仅下载 n = 25 个图像中的第一个,但被调用 25 次(控制台日志“到达此处”多次)。

var evt = document.createEvent("MouseEvents");

evt.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);

[].forEach.call( document.getElementsByClassName("clickit"), function(elem){
  console.log("got here");
  elem.dispatchEvent(evt);
});

I've tried an alternate method, but this code almost immediately crashes chrome (throwing KERN_PROTECTION_FAILURE's in the logs):我尝试了另一种方法,但此代码几乎立即使 chrome 崩溃(在日志中抛出 KERN_PROTECTION_FAILURE):

 for (var i = 0; i < document.getElementsByClassName("clickit").length; i++){ var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.getElementsByClassName("clickit")[i].dispatchEvent(clickEvent); }

In both cases, I have a feeling that I'm using the dispatchEvent() function incorrectly, but I cannot put my finger on it.在这两种情况下,我都觉得我错误地使用了 dispatchEvent() 函数,但我无法解决它。 In the first case, the retrieval of a single image properly is encouraging.在第一种情况下,正确检索单个图像是令人鼓舞的。 I have a feeling I'm falling into bad memory access territory with the second case.我有一种感觉,我在第二种情况下陷入了糟糕的内存访问领域。

Any ideas?有任何想法吗?

I don't know what the problem with your code might be (maybe the fact that document.createEvent() has been deprecated), but I was able to donwload some 90 imgs without chrome complaining about it at all (it may ask you once if you allow the webpage to download multiple images, but that's it). 我不知道您的代码可能存在什么问题(也许是不推荐使用document.createEvent()这一事实),但是我能够下载大约90个没有chrome的imgs抱怨它(它可能会问你一次)如果您允许网页下载多个图像,但就是这样)。
Sample code: 示例代码:

/* Download an img */
function download(img) {
    var link = document.createElement("a");
    link.href = img.src;
    link.download = true;
    link.style.display = "none";
    var evt = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": true
    });

    document.body.appendChild(link);
    link.dispatchEvent(evt);
    document.body.removeChild(link);
    console.log("Downloading...");
}

/* Download all images in 'imgs'. 
 * Optionaly filter them by extension (e.g. "jpg") and/or 
 * download the 'limit' first only  */
function downloadAll(imgs, ext, limit) {
    /* If specified, filter images by extension */
    if (ext) {
        ext = "." + ext;
        imgs = [].slice.call(imgs).filter(function(img) {
            var src = img.src;
            return (src && (src.indexOf(ext, src.length - ext.length) !== -1));
        });
    }

    /* Determine the number of images to download */
    limit = (limit && (0 <= limit) && (limit <= imgs.length))
            ? limit : imgs.length;

    /* (Try to) download the images */
    for (var i = 0; i < limit; i++) {
        var img = imgs[i];
        console.log("IMG: " + img.src + " (", img, ")");
        download(img);
    }
}

As a demonstration, you can go to this FreeImages.co.uk Gallery , open the console and paste the above code, along with the following: 作为演示,您可以访问此FreeImages.co.uk库 ,打开控制台并粘贴上面的代码,以及以下内容:

/* Callback for button's "click" event */
function doit() {
    var imgs = document.querySelectorAll("img");
    downloadAll(imgs, "jpg", -1);
}

/* Create and add a "download" button on the top, left corner */
function addDownloadBtn() {
    var btn = document.createElement("button");
    btn.innerText = "Download all images";
    btn.addEventListener("click", doit);
    btn.style.position = "fixed";
    btn.style.top = btn.style.left = "0px";
    document.body.appendChild(btn);
}
addDownloadBtn();

Then, by clicking the button that appears on the top, left, you'll get yourself a whole bunch of images :) 然后,通过单击顶部,左侧显示的按钮,您将获得一大堆图像:)
(NOTE: Your download folder will get filled with 90 images. Modify the "limit" parameter of downloadAll() to limit them if you wish.) (注意:您的下载文件夹将填充90张图片。如果您愿意,请修改downloadAll()的“limit”参数以限制它们。)

You don't need a chrome extension you could runt this in console or make a bookmarklet: 您不需要Chrome扩展程序,您可以在控制台中使用它或制作书签:

images=document.querySelectorAll("img"); for (i of images) { var a = document.createElement('a'); a.href = i.src; console.log(i); a.download = i.src; document.body.appendChild(a); a.click(); document.body.removeChild(a);}

same thing beautified for reading: 同样美化阅读的东西:

images = document.querySelectorAll("img");
for (i of images) {
    var a = document.createElement('a');
    a.href = i.src;
    console.log(i);
    a.download = i.src;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

Eduard's answer wouldn't work for me using either Chrome, Firefox or Safari until I wrapped it in a setInterval(). 在我将其包装在setInterval()中之前,Eduard的答案对我使用Chrome,Firefox或Safari都不起作用。 An interval of 500 worked for me. 间隔500为我工作。 Less may work but I figured allow a safety margin. 较少可行,但我认为允许安全边际。 Although I can see how that could add up if the image count is high. 虽然我可以看到如果图像数量很高,它会如何加起来。

var i = 0;

var id = setInterval( function() {

    if ( i >= images.length ) {
       clearInterval( id );
       return;
    }

   var image = images[i++];
   i++;
   var a = document.createElement('a');
   console.log( image )
   a.href = image.src
   a.download = image.src
   document.body.appendChild(a);
   a.click();
   document.body.removeChild(a);

}

If you need to download bulk images then you can use below script.如果您需要下载批量图像,则可以使用以下脚本。 Use this script in your developer tool from same website where you want to download images.在您要下载图像的同一网站的开发人员工具中使用此脚本。

For example, if you need to download images from https://testing-images.com/images-1.jpg to https://testing-images/images-34.jpg Then go to https://testing-images.com website and open developer tools and go to console and run below script.例如,如果您需要从https://testing-images.com/images-1.jpg下载图片到 https://testing-images/images-34.jpg 则转到https://testing-images。 com网站并打开开发人员工具,然后转到控制台并在脚本下运行。

for(let i=1; i<35; i++){
  setTimeout(() => {
    fetch(`https://testing-images/images-${i}.jpg`)
      .then(resp => resp.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        // the filename you want
        a.download = `slide-mian-${i}.jpg`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      })
      .catch(() => alert('oh no!'));
  }, i*1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM