网络爬虫之cheerio

cheerio是为服务器特别定制的,快速/灵活/实施的jquery核心实现,适合各种Web爬虫程序。
iconv命令可以将一种已知的字符集文件转换成另一种已知的字符集文件。它的作用是在多种国际编码格式之间进行文本内码的转换。

模块引用

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello World</h2>');
$('.title').text('Hello there!');
$('.title').addClass('welcome');
//输出
console.log($.html());
//输出:<html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
//解析:.load() 引入我们要解析的html。text() 设置 h2 中的文本。addClass() 给 h2 添加新的class。

深度了解cheerio http://www.hubwiz.com/course/5636b7a11bc20c980538e998/

实用:

let request = require('request');
let iconv = require('iconv-lite');

let cheerio = require('cheerio');
//真正得到的是二进制,然后需要转码后才会是字符串
//默认是用utf8编码转换的
request({uri: 'http://top.baidu.com/category?c=1&fr=topindex', encoding: null}, function (err, response, body) {
    body = iconv.decode(body, 'gbk');// iconv 解码 :把buffer类型转成gbk

    let $ = cheerio.load(body);
    $('.hd .title a').each(function (index, item) {
        let $this = $(item);
        let category = {
            name: $this.text(),
            url: $this.attr('href')
        };
        console.log(category);
    })
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值