nodeJs爬蟲的技術(shù)點總結(jié)
背景
最近打算把之前看過的nodeJs相關(guān)的內(nèi)容在復(fù)習(xí)下,順便寫幾個爬蟲來打發(fā)無聊,在爬的過程中發(fā)現(xiàn)一些問題,記錄下以便備忘。
依賴
用到的是在網(wǎng)上爛大街的cheerio庫來處理爬取的內(nèi)容,使用superagent處理請求,log4js來記錄日志。
日志配置
話不多說,直接上代碼:
const log4js = require('log4js'); log4js.configure({ appenders: { cheese: { type: 'dateFile', filename: 'cheese.log', pattern: '-yyyy-MM-dd.log', // 包含模型 alwaysIncludePattern: true, maxLogSize: 1024, backups: 3 } }, categories: { default: { appenders: ['cheese'], level: 'info' } } }); const logger = log4js.getLogger('cheese'); logger.level = 'INFO'; module.exports = logger;
以上直接導(dǎo)出一個logger對象,在業(yè)務(wù)文件里直接調(diào)用logger.info()等函數(shù)添加日志信息就可以,會按天生成日志。相關(guān)信息網(wǎng)絡(luò)上一堆。
爬取內(nèi)容并處理
superagent.get(cityItemUrl).end((err, res) => { if (err) { return console.error(err); } const $ = cheerio.load(res.text); // 解析當前頁面,獲取當前頁面的城市鏈接地址 const cityInfoEle = $('.newslist1 li a'); cityInfoEle.each((idx, element) => { const $element = $(element); const sceneURL = $element.attr('href'); // 頁面地址 const sceneName = $element.attr('title'); // 城市名稱 if (!sceneName) { return; } logger.info(`當前解析到的目的地是: ${sceneName}, 對應(yīng)的地址為: ${sceneURL}`); getDesInfos(sceneURL, sceneName); // 獲取城市詳細信息 ep.after('getDirInfoComplete', cityInfoEle.length, (dirInfos) => { const content = JSON.parse(fs.readFileSync(path.join(__dirname, './imgs.json'))); dirInfos.forEach((element) => { logger.info(`本條數(shù)據(jù)為:${JSON.stringify(element)}`); Object.assign(content, element); }); fs.writeFileSync(path.join(__dirname, './imgs.json'), JSON.stringify(content)); }); }); });
使用superagent請求頁面,請求成功后使用cheerio 來加載頁面內(nèi)容,然后使用類似Jquery的匹配規(guī)則來查找目的資源。
多個資源加載完成,使用eventproxy來代理事件,處理一次資源處罰一次事件,所有事件觸發(fā)完成后處理數(shù)據(jù)。
以上就是最基本的爬蟲了,接下來就是一些可能會出問題或者需要特別注意的地方了。。。
讀寫本地文件
創(chuàng)建文件夾
function mkdirSync(dirname) { if (fs.existsSync(dirname)) { return true; } if (mkdirSync(path.dirname(dirname))) { fs.mkdirSync(dirname); return true; } return false; }
讀寫文件
const content = JSON.parse(fs.readFileSync(path.join(__dirname, './dir.json'))); dirInfos.forEach((element) => { logger.info(`本條數(shù)據(jù)為:${JSON.stringify(element)}`); Object.assign(content, element); }); fs.writeFileSync(path.join(__dirname, './dir.json'), JSON.stringify(content));
批量下載資源
下載資源可能包括圖片、音頻等等。
使用Bagpipe處理異步并發(fā) 參考
const Bagpipe = require('bagpipe'); const bagpipe = new Bagpipe(10); bagpipe.push(downloadImage, url, dstpath, (err, data) => { if (err) { console.log(err); return; } console.log(`[${dstpath}]: ${data}`); });
下載資源,使用stream來完成文件寫入。
function downloadImage(src, dest, callback) { request.head(src, (err, res, body) => { if (src && src.indexOf('http') > -1 || src.indexOf('https') > -1) { request(src).pipe(fs.createWriteStream(dest)).on('close', () => { callback(null, dest); }); } }); }
編碼
有時候直接使用 cheerio.load處理的網(wǎng)頁內(nèi)容,寫入文件后發(fā)現(xiàn)是編碼后的文字,可以通過
const $ = cheerio.load(buf, { decodeEntities: false });
來禁止編碼,
ps: encoding庫和iconv-lite未能實現(xiàn)將utf-8編碼的字符轉(zhuǎn)換為中文,可能是還對API不熟悉,稍后可以關(guān)注下。
最后,附上一個匹配所有dom標簽的正則
const reg = /<.*?>/g;
相關(guān)文章
websocket+node.js實現(xiàn)實時聊天系統(tǒng)問題咨詢
最近新學(xué)習(xí)websocket,做了一個實時聊天。用Node.js搭建的服務(wù):serevr.js. 兩個相互通信頁面:client.html 和server.html 但是就是有很多問題,下面通過本文給大家分享下2017-05-05socket.io學(xué)習(xí)教程之基本應(yīng)用(二)
socket.io提供了基于事件的實時雙向通訊,下面這篇文章主要給大家介紹了socket.io基本應(yīng)用的相關(guān)資料,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-04-04詳解node+express+ejs+bootstrap構(gòu)建項目
本篇文章主要介紹了詳解node+express+ejs+bootstrap構(gòu)建項目,非常具有實用價值,需要的朋友可以參考下2017-09-09nodejs使用socket5進行代理請求的實現(xiàn)
這篇文章主要介紹了nodejs使用socket5進行代理請求的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02