爬虫-抓取图片

const request = require('request')
const cheerio = require('cheerio')
const fs = require('fs')
const path = require('path')
let targetUrl = 'http://............'

request(targetUrl, (err, result, body) => {
  if (err) { throw Error(err) }
  let $ = cheerio.load(body)
  $('img').each( function(i) {
    let imgUrl = $(this).attr('src')
    if (!(imgUrl.includes('https') || imgUrl.includes('http'))) {
      imgUrl = 'http:' + imgUrl
    }
    let pop = imgUrl.split('.').pop()
    request(imgUrl).pipe(fs.createWriteStream( path.join(__dirname, i + '.' + pop), {encoding: 'utf8'}))
  })
})
  • 爬取网页图片 下载到本地目录

你可能感兴趣的:(爬虫-抓取图片)