Node.js 利用cheerio制作简单的网页爬虫示例
本文介绍了Node.js利用cheerio制作简单的网页爬虫示例,分享给大家,具有如下:
1.目标
- 完成对网站的标题信息获取
- 将获取到的信息输出在一个新文件
- 工具:cheerio,使用npm下载npminstallcheerio
- cheerio的API使用方法和jQuery的使用方法基本一致
- 如果熟练使用jQuery,那么cheerio将会很快上手
2.代码部分
介绍:获取segmentfault页面的列表标题,将获取到的标题列表编号,最终输出到pageTitle.txt文件里
consthttps=require('https');
constfs=require('fs');
constcheerio=require('cheerio');
consturl='https://segmentfault.com/';
https.get(url,(res)=>{
lethtml='';
res.on('data',(data)=>{
html+=data;
});
res.on('end',()=>{
getPageTitle(html);
});
}).on('error',()=>{
console.log('获取网页信息错误');
});
functiongetPageTitle(html){
const$=cheerio.load(html);
letchapters=$('.news__item-title');
letdata=[];
letindex=0;
letfileName='pageTitle.txt';
for(leti=0;i{
if(err){
console.log('fs文件系统创建新文件失败',err);
}
console.log(`已成功将获取到的标题放入新文件${fileName}文件中`)
})
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。