Skip to content

Instantly share code, notes, and snippets.

@yo1995
Last active November 25, 2019 22:26
Show Gist options
  • Save yo1995/158ee47d9e9abbc027165a61e9992069 to your computer and use it in GitHub Desktop.
Save yo1995/158ee47d9e9abbc027165a61e9992069 to your computer and use it in GitHub Desktop.
Download all images in a web page
// Image count
var imgTotal = 0;
var imgLoaded = 0;
// Get file name from a URL
function getFileName(o) {
var pos = o.lastIndexOf("/");
return o.substring(pos+1);
}
// Create a tag and make it auto download, then insert to body
var createA = function (obj) {
var a = document.createElement("a");
a.id = obj.id;
a.target = "_blank";
a.href = obj.url;
a.download = imgTotal + ".jpg"; // getFileName(obj.url); // change to incremental order of images in the page
document.body.appendChild(a);
}
// Collect all image tags in the page
var imgs = document.getElementsByTagName("img");
// Create an a tag for all images
for (var i = 0; i < imgs.length;i++){
var obj = {
id: "img_" + i,
url: imgs[i].src
}
// filter image types
if (["JPG", "JPEG"].indexOf(obj.url.substr(obj.url.lastIndexOf(".")+1).toUpperCase()) < 0) {
continue;
}
// ignore images too small
if (imgs[i].width <= 32 || imgs[i].height <= 32) {
continue;
}
imgTotal++;
createA(obj);
}
// Start to download
for (var i = 0; i < imgs.length; i++) {
if (document.getElementById("img_" + i)) {
// invoke the click event of the image object
document.getElementById("img_" + i).click();
imgLoaded++;
}
}
console.log("Downloaded: " + imgLoaded + ", Total: " + imgTotal);
var urls = "";
var count = 0;
var imgs = document.getElementsByTagName("img");
for(var i = 0; i < imgs.length; i++){
if (imgs[i].width <= 100 || imgs[i].height <= 100) {
continue;
}
urls += imgs[i].src;
if(i+1 < imgs.length) urls+="\n";
count += 1;
}
console.log(urls);
console.log("Total " + imgs.length + ", Captured " + count);
@yo1995
Copy link
Author

yo1995 commented Nov 25, 2019

A mirror to the original issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment