NodeJs + Phantomjs 簡易爬蟲
爬蟲是什么?
引用百度百科的說法是:
網(wǎng)絡(luò)爬蟲(又被稱為網(wǎng)頁蜘蛛,網(wǎng)絡(luò)機器人,在FOAF社區(qū)中間,更經(jīng)常的稱為網(wǎng)頁追逐者),是一種按照一定的規(guī)則,自動地抓取萬維網(wǎng)信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。
如何在NodeJs上搭建爬蟲環(huán)境?
-
安裝Phantomjs, 這里我們使用一個集成的NodeJS模塊,GitHub地址
npm i phantom --save-dev -
安裝Cheerio, Cheerio是一個服務(wù)器端基本實現(xiàn)Jquery核心功能的一個庫
npm i cheerio --save-dev
好了,現(xiàn)在我們需要的基本環(huán)境都有了,如何進(jìn)行程序編寫呢?
-
工欲善其事必先利其器,當(dāng)然是先準(zhǔn)備一個好用的IDE??!這里我們選擇WebStorm.
先使用WebStorm創(chuàng)建一個NodeJS-Express項目,這里我們選擇使用EJS模板,如圖:
TIM截圖20180124110558.png項目創(chuàng)建好以后,修改項目的index.js文件。
-
廢話不多說,編寫一個簡易的爬蟲程序。
目的:獲取百度首頁上所有能匹配 http[s]?://.* 的a標(biāo)簽,因此有:
const express = require('express'); const router = express.Router(); const phantom = require('phantom'); const cheerio = require('cheerio'); /* GET home page. */ router.get('/', function (req, res, next) { res.header('Content-Type', 'application/json'); let sitepage = null; //創(chuàng)建網(wǎng)頁對象實例 let phInstance = null; //創(chuàng)建phantomj實例對象 phantom.create() .then(instance => { phInstance = instance; return instance.createPage(); }) .then(page => { sitepage = page; return page.open('https://www.baidu.com/'); }) .then(status => { console.info(status); //獲取結(jié)果狀態(tài) return sitepage.property('content'); //獲取相應(yīng)的屬性內(nèi)容 }) .then(content => { const $ = cheerio.load(content); //解析輸出的結(jié)果內(nèi)容 const jsonResult = []; $('a[href]').each((i, item) => { //抓取符合條件的a標(biāo)簽的鏈接地址 const href = $(item).attr('href'); if (new RegExp(/http[s]?:\/\/.*/).test(href)) { jsonResult.push(href); } }); sitepage.close(); phInstance.exit(); res.json(jsonResult); }) .catch(error => { console.log(error); phInstance.exit(); res.json({status: false}); }); }); module.exports = router;運行以上代碼后,你會看到以下輸出:
TIM截圖20180124111631.png
- 希望你也能成功,**Good Luck! **

