node爬虫(分页+验证+解决编码)

核心模块使用了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
        })
    })
}

欢迎留言~多多交流才能进步!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值