核心模块使用了http、fs。如果是https协议,使用https核心模块。第三方模块使用了cheerio、iconv-lite,记得用 npm i *
安装哦~。如果验证不通过就换换cookie试下吧。
const http = require('http');
const cheerio = require('cheerio'); //nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现,则能够对请求结果进行解析,解析方式和jQuery的解析方式几乎完全相同
const fs = require('fs');
const iconv = require('iconv-lite');
let startPage = 1;
let endPage = 58;
let allBless = [];
const url = '带有页码参数的目标网址,例如http://www.*.com/*/?page=1';
console.log('开始爬取......');
console.log('============================================================第'+startPage+'页==========================================');
getData(url);
function getData(url){
http.get({
hostname: "目标网址的域名或ip地址,例如www.*.com",
port: 80,
path:url,
headers: {
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
"cookie": "使用document.cookie获取"
}
},function(res) {
let html = '';
res.on('data',function(data){
html += data;
});
res.on('end',function(){
getPageData(html);
startPage++;
if(startPage <= endPage){
let tempUrl = '例如http://www.*.com/*/?page=' + startPage;
console.log('============================================================第'+startPage+'页==========================================');
getData(tempUrl);
}else{
fs.writeFile('./bless.json', JSON.stringify(allBless),function(err){
if(!err){
console.log('文件写入完毕');
}
})
}
})
})
}
function getPageData(html){
//解决编码问题
//let html = iconv.decode(Buffer.concat(html),'GBK');
//将页面源代码转为$对象
const $ = cheerio.load(html);
//根据爬取的页面结构找到正确的类名
$('div .wish-box').each(function(){
// this循环时指向当前这个愿望信息
// 相当于this.querySelector
const time = $('.head-bar', this).text().slice(-19);
const content = $('.content',this).text();
const name = $('.user',this).text();
//console.log(name,content,time);
//存入数组
allBless.push({
name,content,time
})
})
}
欢迎留言~多多交流才能进步!