前言
爬蟲,是一種自動獲取網頁內容的程序。是搜索引擎的重要組成部分,因此搜索引擎優化很大程度上就是針對爬蟲而做出的優化。
這篇文章介紹的是利用node.js實現博客小爬蟲,核心的注釋我都標注好了,可以自行理解,只需修改url和按照要趴的博客內部dom構造改一下filterchapters和filterchapters1就行了!
下面話不多說,直接來看實例代碼
var http=require('http');var Promise=require('Bluebird');var cheerio = require('cheerio');var url='http://www.immaster.cn';//博客地址function filterchapters1(html) {//解析文章鏈接 var $ =cheerio.load(html); var post=$('.post'); var content=[]; post.each(function (item) { var postid=$(this).find('.tit').find('a').attr('href'); content.push(postid); }) return content;}function filterchapters(html) {//解析每個文章內的內容 var $ =cheerio.load(html); var tit=$('.post .tit').find('a').text(); var postid=$('.tit').find('a').attr('href'); var commentnum=$('.comments-title').text(); commentnum=commentnum.trim(); // commentnum=commentnum.replace('/n',''); var content={tit:tit,url:postid,commentnum:commentnum}; return content;}function getid(url){//爬取首頁文章鏈接 return new Promise(function (resolve,reject) { http.get(url,function (res) { var html = ''; res.on('data',function(data) { html+=data; }); res.on('end',function () { var content=filterchapters1(html) resolve(content); })}).on('error',function () { reject(e); console.log('抓取出錯!') })})}function getpageAsync(url) {//爬取單個頁面內容 return new Promise(function (resolve,reject) { console.log('正在爬取……'+url) http.get(url,function (res) { var html = ''; res.on('data',function(data) { html+=data; }); res.on('end',function () { resolve(html); }) }).on('error',function () { reject(e); console.log('抓取出錯!') }) })}getid(url) .then(function(postid){ return new Promise(function (resolve,reject) { var pageurls=[]; postid.forEach(function (id) { pageurls.push(getpageAsync(id)); }) resolve(pageurls); }) }) .then(function(pageurls){ return new Promise.all(pageurls);//讓promise對象同時開始運行 }) .then(function (pages) { var coursesData=[]; pages.forEach(function (html) { var courses=filterchapters(html); coursesData.push(courses); })coursesData.forEach(function(v){ console.log('標題:'+v.tit+"/n地址:"+v.url+"/n評論:"+v.commentnum) }) })總結
以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用node.js實現爬蟲能有所幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答