Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
344 lines (291 loc) · 10.9 KB
/
Copy pathapp.js
File metadata and controls
344 lines (291 loc) · 10.9 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
(function (module) {
/* Dependencies */
var request = require('request');
var cheerio = require('cheerio');
var env = process.env.NODE_ENV;
function log(msg) {
if (env === 'dev') {
console.log(msg);
}
}
/* Required vars */
/* We have to have a league ID for anything to work */
var config = {
leagueId: process.argv[2] || null,
methods: [],
seasons: []
};
process.argv.forEach(function (arg, i) {
if (i >= 3) {
config.methods.push(arg);
}
});
var Scraper = function(config) {
config = config || {};
if (!config.leagueId) {
throw new Error('No league id supplied to constructor');
}
this.leagueId = config.leagueId;
this.baseUrl = config.baseUrl || 'http://fantasy.nfl.com/league/' + this.leagueId + '/history';
this.methodsToRun = config.methods || [];
this.seasons = config.seasons || [];
};
Scraper.prototype.init = function () {
var that = this;
this.getSeasons().then(function (seasons) {
that.fireScraper(seasons);
}, function(err) {
log(err);
});
};
Scraper.prototype.fireScraper = function (seasons) {
var that = this;
if (!seasons) {
throw new Error('No seasons to scrape');
}
// If we've got no methods passed in, run everything cuz whaaa
if (that.methodsToRun.length === 0) {
log('No scrape methods supplied. Will run all.');
Object.keys(that.Scrape).forEach(function (key) {
that.Scrape[key].call(that, seasons);
});
} else {
that.methodsToRun.forEach(function (method) {
if(that.Scrape[method] && typeof that.Scrape[method] === 'function') {
that.Scrape[method].call(that, seasons);
}
});
}
};
Scraper.prototype.getSeasons = function () {
var that = this;
return new Promise(function(resolve, reject) {
if (that.seasons.length > 0) {
resolve(that.seasons);
} else {
resolve(that.Scrape.seasons.call(that));
}
});
};
var ScrapeAPI = {};
ScrapeAPI.seasons = function () {
var that = this;
return new Promise(function(resolve, reject) {
request(that.baseUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
that.seasons.length = 0; // clear existing seasons
var $ = cheerio.load(body);
$('#historySeasonNav .st-menu a[href]').each(function (i, el) {
var year = parseInt($(el).text());
that.seasons.push(year);
});
if (that.seasons.length === 0) {
reject(Error('No seasons to scrape'));
} else {
resolve(that.seasons);
}
} else {
reject(Error('Could not access page: ' + error));
}
});
});
};
ScrapeAPI.almanac = function () {
var that = this;
request(that.baseUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var seasons = [];
$('#leagueHistoryAlmanac [class*="history-champ"]').each(function (i, el) {
var $row = $(el);
var year = $row.find('.historySeason').text();
var team = $row.find('.historyTeam .teamName').text();
seasons.push(year);
log(year + ' Champion: ' + team);
});
$('#leagueHistoryAlmanac [class*="history-btw"]').each(function (i, el) {
var $row = $(el);
var year = $row.find('.historySeason').text();
var week = $row.find('.historyWeek').text();
var team = $row.find('.historyTeam .teamName').text();
var points = $row.find('.historyPts').text();
log(year + ' Weekly Points Winner: ' + team + ' with ' + points + ' points in week ' + week);
});
$('#leagueHistoryAlmanac [class*="history-bpw"]').each(function (i, el) {
var $row = $(el);
var year = $row.find('.historySeason').text();
var week = $row.find('.historyWeek').text();
var team = $row.find('.historyTeam .teamName').text();
var player = $row.find('.playerNameAndInfo .playerName').text();
var posTeam = $row.find('.playerNameAndInfo em').text();
var points = $row.find('.historyPts').text();
log(year + ' Weekly Player Points Winner: ' + team + ' with ' + player + ' (' + posTeam + ') with ' + points + ' points in week ' + week);
});
$('#leagueHistoryAlmanac [class*="history-bts"]').each(function (i, el) {
var $row = $(el);
var year = $row.find('.historySeason').text();
var team = $row.find('.historyTeam .teamName').text();
var points = $row.find('.historyPts').text();
log(year + ' Season Points Winner: ' + team + ' with ' + points + ' points');
});
}
});
};
ScrapeAPI.standings = function (seasons) {
var that = this;
seasons.forEach(function (season, i) {
request(that.baseUrl + '/' + season + '/standings', function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
log(season + ' season');
$('#finalStandings #championResults .results li').each(function (i, el) {
var $row = $(el);
var pos = i += 1;
var team = $row.find('.teamName').text();
log(pos + ' : ' + team);
});
}
});
});
};
ScrapeAPI.draft = function (seasons) {
var that = this;
seasons.forEach(function (season, i) {
request(that.baseUrl + '/' + season + '/draftresults?draftResultsDetail=0&draftResultsTab=round&draftResultsType=results', function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
log(season + ' season draft');
$('#leagueDraftResults #leagueDraftResultsResults .results .wrap > ul').each(function (j, el) {
var round = j += 1;
log('Round ' + round);
var $picks = $(el).children('li');
$picks.each(function (k, el) {
var $pick = $(el);
var pick = Number($pick.find('.count').text());
var player = $pick.find('.playerName').text();
var team = $pick.find('.teamName').text();
log('Pick ' + pick + ': ' + player + ' TO ' + team);
});
});
} else {
log(error);
}
});
});
};
ScrapeAPI.owners = function (seasons) {
var that = this;
seasons.forEach(function (season, i) {
request(that.baseUrl + '/' + season + '/owners', function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
$('#leagueOwners .tableWrap tbody tr').each(function (i, el) {
var $row = $(el);
var owner = $row.find('.teamOwnerName').text();
var ownerId = ($row.find('[class*="userId-"]').attr('class')).replace(/(\D)*/, '');
var ownerTeamName = $row.find('.teamName').text();
log(owner + ' (' + ownerId + ') : ' + ownerTeamName);
});
}
});
});
};
/*
Trades are complex.
They are not grouped together on the page, each teams side of the trade is in its own
<tr>, they are grouped by a common class 'transaction-trade-XXXX-Y'
XXXX is the unique id of the trade in this league,
Y is a number between 1 and 4 which corresponds to:
1: Team who offered the trade
2: Team who accepted the trade
3: Any players Team 1 had to drop in the process of completing the trade
4: Any players Team 2 had to drop in the process of completing the trade
*/
ScrapeAPI.trades = function (seasons, pagination) {
var that = this;
var tradeObj = {};
var urlParams = pagination || '?transactionType=trade';
seasons.forEach(function (season, i) {
request(that.baseUrl + '/' + season + '/transactions' + urlParams, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var tradeObj = {};
$('#leagueTransactions .tableWrap tbody > [class*="transaction-trade-"]').each(function (i, el) {
var $row = $(el);
// ignore the dropped players for now, we're only interested in "status" 1 and 2
var tradeId = $row.attr('class').match(/transaction-trade-(.*?)-[12]/);
if (null === tradeId) {
return;
}
tradeId = season + '_' + tradeId[1];
tradeObj[tradeId] = tradeObj[tradeId] || [];
var players = [];
var date = $row.find('.transactionDate').text();
var team = $row.find('.transactionFrom .teamName').text();
var teamId = $row.find('.transactionFrom .teamName').attr('class').replace(/(\D)*/, '');
$row.find('.playerNameAndInfo li').each(function (i, el) {
players.push($(el).find('.playerName').text());
});
var data = {
players: players,
date: date,
team: teamId,
teamName: team
};
tradeObj[tradeId].push(data);
});
log(season);
for (var trade in tradeObj) {
if (tradeObj.hasOwnProperty(trade)) {
var team1 = tradeObj[trade][0];
var team2 = tradeObj[trade][1];
log(trade + ': ' + team1.teamName + ' traded ' + team1.players.join(', ') + ' to ' + team2.teamName + ' for ' + team2.players.join(', ') + ' on ' + team1.date);
}
}
var next = $('#leagueTransactions .paginationWrap .pagination .next a').attr('href');
if (undefined !== next) {
// we have a next link, recursion!
that.Scrape.trades.call(that, [season], next);
}
}
});
});
};
ScrapeAPI.schedule = function (seasons, pagination) {
var that = this;
var urlParams = pagination || 'schedule?leagueId=' + that.leagueId + '&scheduleDetail=1&scheduleType=week&standingsTab=schedule';
seasons.forEach(function (season, i) {
request(that.baseUrl + '/' + season + '/' + urlParams, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var week = parseInt($('#scheduleSchedule .content ul.scheduleWeekNav .selected .title span').text());
var $matchups = $('#scheduleSchedule .content .scheduleContent .matchups .matchup');
$matchups.each(function (i, el) {
var $matchup = $(el);
var team1 = buildTeam($matchup, 1);
var team2 = buildTeam($matchup, 2);
log(season + ' - Week ' + week + ': ' + team1.name + ' ' + team1.score + ' - ' + team2.score + ' ' + team2.name);
});
// next week
var next = $('#scheduleSchedule .weekNav .ww-next a').attr('href');
if (undefined !== next) {
// we have a next week, recursion!
that.Scrape.schedule.call(that, [season], next);
}
}
});
});
};
// helpers and utils
function buildTeam($matchup, team) {
var $team = $matchup.find('.teamWrap-' + team);
return {
name: $team.find('.teamName').text(),
score: $team.find('.teamTotal').text()
};
}
Scraper.prototype.Scrape = ScrapeAPI;
module.exports = Scraper;
var scrapeSession = new Scraper(config);
scrapeSession.init();
}(module));