1. 程式人生 > >node.js爬蟲,牛刀小試

node.js爬蟲,牛刀小試

title data- href console err urn HP pre sha

  暫時未完成,預計端午節前搞完。

  

/**
 * 獲取依賴
 * @type {*}
 */
const superagent = require(‘superagent‘);
const cheerio = require(‘cheerio‘);
const fs = require(‘fs‘);
/**
 * 定義請求地址
 * @type {*}
 */
// const reptileUrl = "http://www.jianshu.com/";
// const reptileUrl = "http://www.imooc.com/learn/348";
const reptileUrl = "http://itianti.sinaapp.com/index.php/gpu/";
/** * 處理空格和回車 * @param text * @returns {string} */ function replaceText(text) { return text.replace(/\n/g, "").replace(/\s/g, ""); } /** * 核心業務 * 發請求,解析數據,生成數據 */ superagent.get(reptileUrl).end(function (err, res) { // 拋錯攔截 if (err) { throw new Error(err); } console.log(res.text)
// 解析數據 let $ = cheerio.load(res.text); /** * 存放數據容器 * @type {Array} */ let data = []; // 獲取數據 $(‘#list-container .note-list li‘).each(function (i, elem) { let _this = $(elem); data.push({ id: _this.attr(‘data-note-id‘), slug: _this.find(
‘.title‘).attr(‘href‘).replace(/\/p\//, ""), author: { slug: _this.find(‘.avatar‘).attr(‘href‘).replace(/\/u\//, ""), avatar: _this.find(‘.avatar img‘).attr(‘src‘), nickname: replaceText(_this.find(‘.blue-link‘).text()), sharedTime: _this.find(‘.time‘).attr(‘data-shared-at‘) }, title: replaceText(_this.find(‘.title‘).text()), abstract: replaceText(_this.find(‘.abstract‘).text()), thumbnails: _this.find(‘.wrap-img img‘).attr(‘src‘), collection_tag: replaceText(_this.find(‘.collection-tag‘).text()), reads_count: replaceText(_this.find(‘.ic-list-read‘).parent().text()) * 1, comments_count: replaceText(_this.find(‘.ic-list-comments‘).parent().text()) * 1, likes_count: replaceText(_this.find(‘.ic-list-like‘).parent().text()) * 1 }); }); // 生成數據 // 寫入數據, 文件不存在會自動創建 fs.writeFile(__dirname + ‘/data/article.json‘, JSON.stringify({ status: 0, data: data }), function (err) { if (err) throw err; console.log(‘寫入完成‘); }); });

主要參考這兩篇文章10分鐘教你擼一個nodejs爬蟲系統 Node.js學習之網絡爬蟲(使用cheerio抓取網頁數據) ,但由於歷史原因,一些代碼已經不可用了,根據這兩篇文章的思想,自己重寫一個Node.js爬蟲。

node.js爬蟲,牛刀小試