-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
71 lines (55 loc) · 2.09 KB
/
parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
var ESLParser = function() {
console.log('\x1b[36m', 'Started parsing ESL Podcast pages... This may take some time.' ,'\x1b[0m');
this.actualPage = 1;
this.episodes = [];
var that = this;
ESLParser.prototype.request = function(url, fromEpisode, toEpisode, callback) {
url = url || constants.BASE_URL;
this.fromEpisode = this.fromEpisode || fromEpisode;
this.toEpisode = this.toEpisode || toEpisode;
this.callback = this.callback || callback;
var request = require('request');
request(url, function(error, response, html) {
if(!error) {
that.parse(html);
} else {
throw new Error();
}
});
}
ESLParser.prototype.parse = function(html) {
var cheerio = require('cheerio');
var $ = cheerio.load(html),
mainContentTD = $('body > table:nth-child(2) > tr > td:nth-child(3) > table > tr:nth-child(2) > td:nth-child(2)');
var totalEpisodes = $('b', $('table', mainContentTD).first()).first().text(),
nextPageUrl = $('a:contains("next")', $('table', mainContentTD).first()).last().attr('href') || '',
episodesTables = $('table', mainContentTD).first().nextAll('table[cellpadding!="1"]');
var mapEpisodes = (function(){
var slug = require('slug');
episodesTables.map(function(index, episodeTable) {
var obj = {},
title = slug($('.podcast_title', episodeTable).text()),
link = $('a[href$=".mp3"]', episodeTable).attr('href') || null;
obj.title = title;
obj.link = link;
that.storeEpisode(obj);
});
})();
this.paginateTo(nextPageUrl);
}
ESLParser.prototype.storeEpisode = function(episode) {
this.episodes.push(episode);
}
ESLParser.prototype.paginateTo = function(nextPageUrl) {
var episodeNumber = nextPageUrl.replace(/.*=(\d+)$/, '$1');
if(nextPageUrl && this.episodes.length <= this.toEpisode) {
console.log('Requesting page ', constants.BASE_URL + episodeNumber);
this.request(constants.BASE_URL + episodeNumber);
} else {
console.info('\x1b[36m', 'Parse completed. ' + this.episodes.length + ' episodes crawled' ,'\x1b[0m');
this.callback(this.episodes);
}
}
};
module.exports = new ESLParser();