爬虫下载图片的问题
发布于 1个月前 作者 ThinkCats 203 次浏览 来自 问答

写一个爬虫,当只下载比较少的图片时候,一切正常,当下载比较多的图片的时候,会报错。我这里试了两种方式,都会出问题。 1.采用child_process,调用系统的curl下载图片。 代码: var curl=cp.spawn('curl’,[file_url]); curl.stdout.on('data’,function(data){ file.write(data); }); curl.stdout.on('end’,function(data){ file.end(); console.log(filename+’download to’+DOWNLOAD_DIR); }); 这里省去了on(‘error’)和on(‘exit’) 。最终只能下载几个图片,很多都是失败的,然后报错。 这个报的错误是这样: Error: spawn EMFILE at errnoException (child_process.js:988:11) at ChildProcess.spawn (child_process.js:935:11) at Object.exports.spawn (child_process.js:723:9)

2.所以又采用第二种方式,用http来get这些图片。 var filename=url.parse(file_url).pathname.split(‘/’).pop(); var file=fs.createWriteStream(DOWNLOAD_DIR+filename); http.get(file_url,function(res){ res.on('data’,function(data){ file.write(data); }); res.on('end’,function(data){ file.end(); }); res.on('error’,function(e){ if(e){ console.log('Errored:’+e); file.end(); }else{ console.log(‘Finish’); } }); }); 这样的效果更不好,也报错了,报的错误是: read econnreset 请教各位,当下载很多图片的时候,要怎么处理呢?

2 回复

限制并发用 async.parallelLimit https://github.com/caolan/async#parallellimittasks-limit-callback

不知道Promise有没有 parallelLimit

@magicdawn 的确应该是这个并发的原因 我代码里面是没一点限制的

回到顶部