nodejs制作小爬虫功能示例
更新时间:2020年02月24日 10:44:11 作者:巴啦啦小能量
这篇文章主要介绍了nodejs制作小爬虫功能,结合实例形式分析了node.js安装request、cheerio模块及请求发送、数据库操作等相关实现技巧,需要的朋友可以参考下
本文实例讲述了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程序设计有所帮助。
相关文章
Node.js 连接 MySql 统计组件属性的使用情况解析
这篇文章主要为大家介绍了Node.js 连接 MySql 统计组件属性的使用情况解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10使用 Node.js和Express搭建服务器的过程步骤详解
Node.js 是一个开源、跨平台的 JavaScript 运行时环境,这篇文章主要介绍了如何使用 Node.js和Express搭建服务器,需要的朋友可以参考下2023-09-09
最新评论