背景
最近打算把之前看過的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); // 解析當(dāng)前頁面,獲取當(dāng)前頁面的城市鏈接地址 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(`當(dāng)前解析到的目的地是: ${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標(biāo)簽的正則
const reg = /<.*?>/g;
新聞熱點
疑難解答