对于http模块实现简单的爬虫
爬虫:就是用来爬取网页的内容;
1:使用步骤
- 项目中安装
npm install cheerio --save-dev
- 引入
const cheerio = require('cheerio')
- 装载
const $ = cheerio.load('<div>JavaScript是一门不错的语言</div>');
- 使用相应的API
2:cheerio 模块
在nodejs中,可以使用 http 和 https 模块来实现简单的爬虫。会使用到一个cheerio 模块 。该模块可以将返回的字符串转为 jQuery 中的 $ 对象,从而可以使用 jQuery 中的各种方法。
示例如下:
const https = require('https');
const cheerio = require('cheerio');
https.get('https://tuijian.hao123.com/hotrank',(res)=>{
let data = ''; // 装回来的数据
res.on('data',(chunk)=>{
data += chunk
});
res.on('end',()=>{
filter(data);
})
})
function filter(data){
let result = []; // 存放筛选后的数据
const $ = cheerio.load(data); // 将字符串传递给 cheerio 模块,会生成一个 jQuery 对象,我们就可以在服务器端使用 jQuery 方法
const temp_arr = $('[monkey="ss"]').find('.point-bd').find('.point-title')
temp_arr.each((index,item)=>{
result.push($(item).text());
})
console.log(result);
}