nodejs制作小爬虫功能示例
本文实例讲述了nodejs制作小爬虫功能。分享给大家供大家参考,具体如下:
1安装nodejs
2安装需要模块
npminstallrequestcheerio
3新建js文件
4引入
constrequest=require("request")
constcheerio=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遍历
varnewsTitle=$(this).children('a').text();//得到标签的文字
varnewsTime=$(this).children('span').eq(1).text();//得到第二个标签的文字
varnewsUrl="http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到标签的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遍历
varnewsTitle=$(this).children('a').text();//得到标签的文字
varnewsTime=$(this).children('span').eq(1).text();//得到第二个标签的文字
varnewsUrl="http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到标签的href的值
item++;
console.log("已爬取"+item+"条记录");
});
}
});
下面的带数据库
constrequest=require("request")
constcheerio=require("cheerio")
constmysql=require('mysql')
constdb=mysql.createPool({host:'120.79.5554',user:'root',password:'root',database:'pachong'});
varitem=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遍历
varnewsTitle=$(this).children('a').text();//得到标签的文字
varnewsTime=$(this).children('span').eq(1).text();//得到第二个标签的文字
varnewsUrl="http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到标签的href的值
console.log(newsTitle,newsTime,newsUrl)
db.query(`INSERTINTOnews(newsTitle,newsTime,newsUrl)VALUE('${newsTitle}','${newsTime}','${newsUrl}')`,function(err,data){
if(err)
{
console.log("数据库连接错误");
}
})
item++;
console.log("已爬取"+item+"条记录");
});
}
});
希望本文所述对大家node.js程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。