要准备下载的图片:
代码:
const http = require('http')
const cheerio = require('cheerio')
const download = require('download')
const HOST = 'http://www.18183.com/yxzjol/?soucre=bdald'
let req = http.request(HOST, res => {
//异步的响应
// console.log(res)
//监听data事件,并获取传递过来的数据片段
//拼接数据片段
let chunks=[]
res.on('data', chuck => {
chunks.push(chuck)
})
//监听end事件,获取数据完毕时触发
res.on('end', () => {
//拼接所有的chuck,并转化或字符串==》html字符串
//console.log(Buffer.concat(chunks).toString('utf-8'))
let htmlStr = Buffer.concat(chunks).toString('utf-8')
let $ = cheerio.load(htmlStr)
//$('.pic-menu ul li img ').each( function (index, item) {
// console.log(index,item)
// console.log($(item).attr('src'))
//})
//获取图片
let imgs = Array.prototype.map.call($('.pic-menu ul li img '), item => $(item).attr('src'))
//let imgs= $('.pic-menu ul li img ').map((index,item) => $(item).attr('src'))
// console.log(imgs[0])
console.log(imgs)
//下载图片
Promise.all(imgs.map(x => download(x, 'dist'))).then(() => {
console.log('Download complete');
})
})
})
//将请求发出
req.end()
注意:引入cheerio,download包
完成效果: