node. js 파충 류 는 웹 페이지 그림 을 기어 올 라 로 컬 에 저장 합 니 다.
14003 단어 nodeJs
잔말 말고 코드 봐.
/**
*
*
*/
// ,http https
const http = require('http')
const fs = require('fs')
const cheerio = require('cheerio') // html jq ( node npm )
let url = 'http://www.xiongmaoyouxuan.com' //text/html
let json = 'http://nodejs.org/dist/index.json'//application/json
http.get(url,(res)=>{
//
const {statusCode} = res //
const contentType = res.headers['content-type'] //
let err =null
if(statusCode !==200){
err = new Error(' '+statusCode)
} else if(!/^text\/html/.test(contentType)) {
err = new Error(' '+contentType)
}
if (err){
console.log(err)
res.resume()//
return false
}
//
// , data , chunk
let rawData = ''
res.on('data',(chunk)=>{
// console.log( chunk.toString('utf8'));
rawData += chunk.toString('utf-8')// utf-8
})
//
res.on('end',()=>{
//
let $ = cheerio.load(rawData)// jq
$('img').each((index,item)=>{
saveImg($(item).attr('src'),index+'wilteMe.png')
})
//
fs.writeFile('./xiongmaoyouxuan.html',rawData,(err)=>{
if(err){
console.log(' ');
} else {
console.log(' ');
}
})
console.log(' ');
})
}).on('error',(err)=>{
console.log(' ');
})
//
function saveImg(url,path) {
console.log(url,path)
try{
http.get(url,function (req,res) {
var imgData = '';
req.setEncoding('binary');
req.on('data',function (chunk) {
imgData += chunk;
})
req.on('end',function () {
fs.writeFile(path,imgData,'binary',function (err) {
console.log(' '+path)
})
})
})
}
catch(err){
}
}