Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js脚本下载网页图片 #109

Open
imuncle opened this issue Apr 21, 2020 · 0 comments
Open

js脚本下载网页图片 #109

imuncle opened this issue Apr 21, 2020 · 0 comments
Labels
web web开发点滴

Comments

@imuncle
Copy link
Owner

imuncle commented Apr 21, 2020

今天遇到一个小需求,要将一个网页中的图片都下载下来,有一百多个图片,手动右键另存为不太现实,是时候使用脚本了。

F12打开调试窗口,复制输入以下代码:

//一个对象,存储页面图片数量和下载的数量
var monitorObj = {
    imgTotal: 0,
    imgLoaded: 0
}
//创建a标签,赋予图片对象相关属性,并插入body
var createA = function (obj, index) {
    var a = document.createElement("a");
	a.id = obj.id;
    a.target = "_blank";//注意:要在新页面打开
    a.href = obj.url;
    a.download = index+".jpg";

    document.body.appendChild(a);
}

//获取页面的图片
var imgs = document.images;
//创建每个图片对象的对应a标签
for (var i = 0; i < imgs.length;i++){
    var obj = {
        id: "img_" + i,
        url: imgs[i].src
    }
    //过滤掉不属于这几种类型的图片
    //if (["JPG", "JPEG", "PNG","GIF"].indexOf(obj.url.substr(obj.url.lastIndexOf(".")+1).toUpperCase()) < 0) {
    //    continue;
    //}
    //这里是为了去掉知乎用户头像的图片,头像大小是50*50
    if (imgs[i].width <= 50 || imgs[i].height <= 50) {
        continue;
    }
    //统计图片数量
    monitorObj.imgTotal++;
    createA(obj, i+1);
}

var sleep = function(time) {
    var startTime = new Date().getTime() + parseInt(time, 10);
    while(new Date().getTime() < startTime) {}
};

//开始下载图片
for (var i = 0; i < imgs.length; i++) {
    if (document.getElementById("img_" + i)) {
        //重点:触发a标签的click事件        
        document.getElementById("img_" + i).click();
		sleep(500);
        monitorObj.imgLoaded++; //统计已下载的图片数量
   } 
} 
console.log("已下载:"+monitorObj.imgLoaded + "/" + monitorObj.imgTotal);

然后回车就行了。

这里我把判断图片格式的代码注释掉了,如果需要可以加上去。另外我还加了一个sleep()函数,因为我测试的时候没有这个延时只能下载前10个,后续可以考虑改进为打包为压缩包下载

@imuncle imuncle added the web web开发点滴 label Apr 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web web开发点滴
Projects
None yet
Development

No branches or pull requests

1 participant