本文实例讲述了nodejs制作小爬虫功能。分享给大家供大家参考,具体如下:
1 安装nodejs
2 安装需要模块
npm install request cheerio
3 新建js文件
4 引入
const request=require("request") const cheerio=require("cheerio")
5 利用request模块发送请求
request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){ if(err) { console.log('请求出错'); } else { var $ = cheerio.load(res.body, {decodeentities: false}); $('.listlist').children('ul').children('li').each(function(){ //找到li元素对象然后通过each遍历 var newstitle = $(this).children('a').text(); //得到<a>标签的文字 var newstime= $(this).children('span').eq(1).text();//得到第二个<span>标签的文字 var newsurl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>标签的href的值 item++; console.log("已爬取"+item+"条记录"); }); } });
一个小爬虫案例就完了
附上完整代码
request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){ if(err) { console.log('请求出错'); } else { var $ = cheerio.load(res.body, {decodeentities: false}); $('.listlist').children('ul').children('li').each(function(){ //找到li元素对象然后通过each遍历 var newstitle = $(this).children('a').text(); //得到<a>标签的文字 var newstime= $(this).children('span').eq(1).text();//得到第二个<span>标签的文字 var newsurl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>标签的href的值 item++; console.log("已爬取"+item+"条记录"); }); } });
下面的带数据库
const request=require("request") const cheerio=require("cheerio") const mysql=require('mysql') const db=mysql.createpool({host:'120.79.5554',user:'root',password:'root',database:'pachong'}); var item=0; request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){ if(err) { console.log('请求出错'); } else { var $ = cheerio.load(res.body, {decodeentities: false}); $('.listlist').children('ul').children('li').each(function(){ //找到li元素对象然后通过each遍历 var newstitle = $(this).children('a').text(); //得到<a>标签的文字 var newstime= $(this).children('span').eq(1).text();//得到第二个<span>标签的文字 var newsurl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>标签的href的值 console.log(newstitle,newstime,newsurl) db.query(`insert into news (newstitle, newstime, newsurl) value('${newstitle}', '${newstime}','${newsurl}')`,function(err,data){ if(err) { console.log("数据库连接错误"); } }) item++; console.log("已爬取"+item+"条记录"); }); } });
希望本文所述对大家node.js程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
使用npm命令提示: 'npm' 不是内部或外部命令,也不是可运行的程序的处理方法
Node Express用法详解【安装、使用、路由、中间件、模板引擎等】
Node Mongoose用法详解【Mongoose使用、Schema、对象、model文档等】
网友评论