Cheerio爬虫-解决网易GBK字符的乱码问题

时间:2022-07-23
本文章向大家介绍Cheerio爬虫-解决网易GBK字符的乱码问题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.爬了网易科技的最新快讯,发现出来的全是乱码。

1.png

2.看了源代码,发现网页字符格式是GBK

2.png


3.于是百度,发现要用到库npm install iconv-lite


4.发现了一个大神写的node库npm install gbk

3.png

看了index.js发现先要有个iconv-lite库

4.png 跑了一遍他git上的example,发现报错。。。。

看到issue中也有人提出相关问题

5.png

很幸运,作者四天前刚刚解决了他的问题。

6.png 直接复制他修改后的page.js替换自己node_modules/gbk/libs/page.js的代码 就可以运行啦!!!


5.然后当然是直接引入到我的代码里。。。

7.png


6.运行结果

8.png

9.png


7.最后贴出全部代码

var http = require('http');
var cheerio = require('cheerio');
var url = 'http://tech.163.com';
var fs =require('fs');
var iconv = require('iconv-lite');
var gbk = require('gbk');
var i=1;
var section_add=null;


http.get(url, function(res){
    //转换gbk字符格式的网页
    gbk.fetch(url).to('string', function(err, string){
        if (err) 
            return console.log(err);
        var chapter=crawlerChapter(string);
        printInfo(chapter);
    });
    // var html = '';
    // res.on('data', function(data){
    //     html+= data;
    //     console.log(html);
    // });
    
}).on('error', function(){
    console.log('爬取页面错误');
});


function crawlerChapter(html) {
    var $ = cheerio.load(html);
    var chapters = $('.newest-lists');//css选择器
    var data = [];
    chapters.map(function (node) {
        var chapters = $(this);
        var chapterTitle = chapters.find('.list_item').text().trim();//选择器
        var sections = chapters.find('.nl-title');//选择器
        var chapterData = {
            chapterTitle: chapterTitle,
            section: []
        };
        sections.map(function (node) {
            var section = $(this).text().trim();
            chapterData.section.push(section);
        });
        data.push(chapterData);
    });
    return data;
}


function printInfo(data) {
    data = data.filter(function filterByID(obj) {
        return obj.chapterTitle ? true : false;
    });
    data.map(function (item) {
        var chapterTitle = item.chapterTitle;
        //console.log('【' + chapterTitle + '】n');未处理的文字

        item.section.map(function (section) {
            console.log('   【' + section + '】n');//换行后的文字
            
            section_add+=section+'n';
           
            
            // ------------------将文字存入文件-----------
            fs.writeFile('./wangyi.txt',section_add,function(err){
                if(err) throw err;
                console.log("file save!"+i);
                i= i+1;
            });
            // ------------------将文字存入文件-----------
        

        });
    });
}