基於nodejs 的多頁面爬蟲

來源:互聯網
上載者:User

標籤:ade   npm   屏蔽   gettime   ==   preview   callback   核心   strong   

前言

前端時間再回顧了一下node.js,於是順勢做了一個爬蟲來加深自己對node的理解。 
主要用的到是request,cheerio,async三個模組 
request 
用於請求地址和快速下載圖片流。 
https://github.com/request/request 
cheerio 
為伺服器特別定製的,快速、靈活、實施的jQuery核心實現. 
便於解析html代碼。 
https://www.npmjs.com/package/cheerio 
async 
非同步呼叫,防止堵塞。 
http://caolan.github.io/async/

核心思路
  • 用request 發送一個請求。擷取html代碼,取得其中的img標籤和a標籤。
  • 通過擷取的a表情進行遞迴調用。不斷擷取img地址和a地址,繼續遞迴
  • 擷取img地址通過request(photo).pipe(fs.createWriteStream(dir + “/” + filename));進行快速下載。
function requestall(url) {  request({    uri: url,    headers: setting.header  }, function (error, response, body) {    if (error) {      console.log(error);    } else {      console.log(response.statusCode);      if (!error && response.statusCode == 200) {        var $ = cheerio.load(body);        var photos = [];        $(‘img‘).each(function () {          // 判斷地址是否存在          if ($(this).attr(‘src‘)) {            var src = $(this).attr(‘src‘);            var end = src.substr(-4, 4).toLowerCase();            if (end == ‘.jpg‘ || end == ‘.png‘ || end == ‘.jpeg‘) {              if (IsURL(src)) {                photos.push(src);              }            }          }        });        downloadImg(photos, dir, setting.download_v);        // 遞迴爬蟲        $(‘a‘).each(function () {          var murl = $(this).attr(‘href‘);          if (IsURL(murl)) {            setTimeout(function () {              fetchre(murl);            }, timeout);            timeout += setting.ajax_timeout;          } else {            setTimeout(function () {              fetchre("http://www.ivsky.com/" + murl);            }, timeout);            timeout += setting.ajax_timeout;          }        })      }    }  });}

  

防坑

1.在request通過圖片地址下載時,綁定error事件防止爬蟲異常的中斷。 
2.通過async的mapLimit限制並發。 
3.加入請求前序,防止ip被屏蔽。 
4.擷取一些圖片和超連結位址,可能是相對路徑(待考慮解決是否有通過方法)。

function downloadImg(photos, dir, asyncNum) {  console.log("即將非同步並發下載圖片,當前並發數為:" + asyncNum);  async.mapLimit(photos, asyncNum, function (photo, callback) {    var filename = (new Date().getTime()) + photo.substr(-4, 4);    if (filename) {      console.log(‘正在下載‘ + photo);      // 預設      // fs.createWriteStream(dir + "/" + filename)      // 防止pipe錯誤      request(photo)        .on(‘error‘, function (err) {          console.log(err);        })        .pipe(fs.createWriteStream(dir + "/" + filename));      console.log(‘下載完成‘);      callback(null, filename);    }  }, function (err, result) {    if (err) {      console.log(err);    } else {      console.log(" all right ! ");      console.log(result);    }  })}

  



測試:

可以感覺到速度還是比較快的。


完整地址。https://github.com/hua1995116/node-crawler/

基於nodejs 的多頁面爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.