-
Notifications
You must be signed in to change notification settings - Fork 6
/
fb.js
231 lines (219 loc) · 9.46 KB
/
fb.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
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
var fs = require('fs'),
vo = require('vo'),
sleep = require('sleep'),
colors = require('colors'),
prompt = require('readline-sync'),
cheerio = require('cheerio'),
Nightmare = require('nightmare');
var currentTimeStamp = Date.now();
var botDebugMode = false;
var args = process.argv.slice(2);
if (args.length > 0 && args[0] === '--debug') { botDebugMode = true; }
init();
function init() {
console.log('----------------------------------');
console.log(' FB Search Scraper BOT v0.1 '.bold.green);
console.log('----------------------------------');
if (botDebugMode === true) { console.log('* Bot initiated in mode debug.'.bold.yellow); }
setStatus('Running bot..');
main();
}
function main() {
var targetUrl = prompt.question('Insert a target url: '.bold);
logInFacebook(getAccountData(), function(loginStatus) {
if (loginStatus === true) {
scrapeFbResultsData(targetUrl);
}
});
}
function logInFacebook(accountData, callback) {
setStatus('Logging to Facebook.com..');
var nightmare = new Nightmare({
width: 800,
height: 600,
'use-content-size': true,
show: botDebugMode,
'web-preferences': {
partition: 'persist:' + currentTimeStamp,
images: false,
webaudio: false,
webgl: false,
'page-visibility': true
}
});
vo(function*() {
yield nightmare
.useragent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36')
.goto('https://m.facebook.com')
.type('input[name="email"]', accountData[0])
.type('input[name="pass"]', accountData[1])
.click('button[name="login"]')
.wait(1250)
var loginStatus = yield nightmare.exists('form[action="/friends/center/search/"]')
yield nightmare
.run(function(err, nightmare) {
if (err) {
console.log(err);
process.exit();
}
})
yield nightmare.end()
if (loginStatus === true) {
setStatus('Bot logged on Facebook with ' + accountData[0].bold + ' successfully..');
callback(true);
} else {
setError("Bot can't login to Facebook.com, check your account.");
callback(false);
process.exit();
}
})(function() {});
}
function scrapeFbResultsData(targetUrl) {
verifyTargetUrl(targetUrl, function(targetUrlVerification) {
if (targetUrlVerification === true) {
var nightmare = new Nightmare({
width: 800,
height: 600,
'use-content-size': true,
show: botDebugMode,
'web-preferences': {
partition: 'persist:' + currentTimeStamp,
images: false,
webaudio: false,
webgl: false,
'page-visibility': true
}
});
vo(function*() {
setStatus('Navigating to target url..');
yield nightmare
.useragent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36')
.goto(targetUrl)
.wait(1000)
var pageHeight = yield nightmare.evaluate(function() { return document.body.scrollHeight });
var bottomDetected = false;
var t0 = new Date().getTime();
var scrollDownCount = 1;
var scrapedFbIds = {};
var elementsToHide = {};
var numFbIdsLastRound = 0;
var WAIT_CONST = 525;
do {
var scrapedResults = yield nightmare.evaluate(function() {
var currentScrapedIds = [];
var currentElements = document.querySelectorAll('div[data-xt]');
for (var i = 0; i < currentElements.length; i++) {
if (currentElements[i].getAttribute('style') === null) {
currentScrapedIds.push(currentElements[i].childNodes[0].lastChild.getAttribute('data-store'));
}
}
return {
'scrapedIds': currentScrapedIds,
}
});
if (scrapedResults.scrapedIds.length > 0) {
for (var n = 0; n < scrapedResults.scrapedIds.length; n++) {
var calcObjPos = {
1: {
"obj": "scrapedFbIds",
"length": Object.keys(scrapedFbIds).length
},
2: {
"obj": "elementsToHide",
"length": Object.keys(elementsToHide).length
}
};
scrapedFbIds[calcObjPos[1].length] = JSON.parse(scrapedResults.scrapedIds[n]);
elementsToHide[calcObjPos[2].length] = JSON.parse(scrapedResults.scrapedIds[n]);
}
}
setStatus('* Scrolling down in search results... #' + scrollDownCount);
yield nightmare
.scrollTo(pageHeight, 0)
if (Object.keys(elementsToHide).length > 0) {
var numElementsToHide = Object.keys(elementsToHide).length;
for (var i = 0; i < numElementsToHide; i++) {
yield nightmare
.wait(WAIT_CONST)
.evaluate(function(elementId) {
document.querySelector('div[data-xt*="' + elementId + '"]').style.display = 'none';
}, elementsToHide[i].result_id)
delete elementsToHide[i];
}
}
if (Object.keys(scrapedFbIds).length === numFbIdsLastRound) { endOfResultsDetected = true; } else { endOfResultsDetected = false; }
if (endOfResultsDetected === true) {
yield nightmare.end();
bottomDetected = true;
setStatus('Facebook end of results detected..');
if (Object.keys(scrapedFbIds).length > 0) {
var t2 = new Date().getTime();
var timeOperation = t2 - t0;
saveScrapedResultsToTxt(scrapedFbIds);
console.log('------------------------------------------------------------');
console.log('Total results scraped: ' + colors.bold.green('%s'), Object.keys(scrapedFbIds).length);
console.log('Scraping operation done in ' + colors.bold.yellow('%s'), timeOperation + 'ms');
console.log('Scraped results have been saved in results_' + currentTimeStamp + '.txt');
console.log('------------------------------------------------------------');
} else {
setError('0 urls have been scraped, check the target url you inserted.');
process.exit();
}
}
numFbIdsLastRound = Object.keys(scrapedFbIds).length;
scrollDownCount++;
}
while (bottomDetected === false);
})(function() {});
} else {
process.exit();
}
});
}
function verifyTargetUrl(targetUrl, callback) {
var targetUrlCallBack = false;
setStatus('Verifying target url..');
if (targetUrl.length > 0) {
if (targetUrl.indexOf('m.facebook.com') > -1) {
setStatus('Target url is valid..');
targetUrlCallBack = true;
} else {
setError("Target url must contain m.facebook.com domain.");
}
} else {
setError("Target URL can't be empty.");
}
callback(targetUrlCallBack);
}
function saveScrapedResultsToTxt(results) {
setStatus('Saving scraped results to txt file..');
var file = fs.createWriteStream('results_' + currentTimeStamp + '.txt');
file.on('error', function(err) {
console.log(err);
process.exit();
});
for (var i = 0; i < Object.keys(results).length; i++) {
if (i + 1 === Object.keys(results).length) {
file.write('https://m.facebook.com/' + results[i].result_id);
} else {
file.write('https://m.facebook.com/' + results[i].result_id + '\n');
}
}
file.end();
}
function setStatus(text) {
console.log('Status: ' + text.strikethrough.cyan);
}
function setError(text) {
console.log('Error: ' + text.bold.red);
}
function getAccountData() {
setStatus('Checking account data file..');
if (fs.existsSync('account_data.txt')) {
setStatus('Account data file found and loaded..');
return fs.readFileSync('account_data.txt').toString().split(";");
} else {
console.log('Error: account_data.txt file not exists.'.bold.red);
process.exit();
}
}