-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
AuthenticatedStrategy.ts
697 lines (598 loc) · 24.1 KB
/
AuthenticatedStrategy.ts
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
import { config } from "../../config";
import { RunStrategy, IRunStrategyResult, ILoadResult } from "./RunStrategy";
import { BrowserContext, Page, CDPSession } from "puppeteer";
import { events, IMetrics } from "../events";
import { sleep } from "../../utils/utils";
import { normalizeString } from "../../utils/string";
import { IQuery } from "../query";
import { logger } from "../../logger/logger";
import { urls } from "../constants";
export const selectors = {
container: '.jobs-search-results-list',
chatPanel: '.msg-overlay-list-bubble',
jobs: 'div.job-card-container',
link: 'a.job-card-container__link',
applyBtn: 'button.jobs-apply-button[role="link"]',
title: '.artdeco-entity-lockup__title',
company: '.artdeco-entity-lockup__subtitle',
companyLink: 'a.job-card-container__company-name',
place: '.artdeco-entity-lockup__caption',
date: 'time',
description: '.jobs-description',
detailsPanel: '.jobs-search__job-details--container',
detailsTop: '.jobs-details-top-card',
details: '.jobs-details__main-content',
insights: '[class=jobs-unified-top-card__job-insight]', // only one class
pagination: '.jobs-search-two-pane__pagination',
privacyAcceptBtn: 'button.artdeco-global-alert__action',
paginationNextBtn: 'li[data-test-pagination-page-btn].selected + li',
paginationBtn: (index: number) => `li[data-test-pagination-page-btn="${index}"] button`,
};
/**
* @class AuthenticatedStrategy
* @extends RunStrategy
*/
export class AuthenticatedStrategy extends RunStrategy {
/**
* Check if session is authenticated
* @param {Page} page
* @returns {Promise<boolean>}
* @returns {Promise<ILoadResult>}
* @static
* @private
*/
private static _isAuthenticatedSession = async (page: Page): Promise<boolean> => {
const cookies = await page.cookies();
return cookies.some(e => e.name === "li_at");
};
/**
* Load jobs
* @param page {Page}
* @param jobsTot {number}
* @param timeout {number}
* @static
* @private
*/
private static _loadJobs = async (
page: Page,
jobsTot: number,
timeout: number = 2000,
): Promise<any> => {
const pollingTime = 50;
let elapsed = 0;
await sleep(pollingTime);
try {
while (elapsed < timeout) {
const jobsCount = await page.evaluate((selector) => {
return document.querySelectorAll(selector).length;
}, selectors.jobs);
if (jobsCount > jobsTot) {
return { success: true, count: jobsCount };
}
await sleep(pollingTime);
elapsed += pollingTime;
}
}
catch (err) {}
return {
success: false,
error: `Timeout on loading jobs`
};
};
/**
* Try to load job details
* @param {Page} page
* @param {string} jobId
* @param {number} timeout
* @static
* @private
*/
private static _loadJobDetails = async (
page: Page,
jobId: string,
timeout: number = 2000,
): Promise<ILoadResult> => {
const pollingTime = 50;
let elapsed = 0;
let loaded = false;
await sleep(pollingTime);
try {
while (elapsed < timeout) {
loaded = await page.evaluate(
(jobId, panelSelector, descriptionSelector) => {
const detailsPanel = document.querySelector(panelSelector) as HTMLElement;
const description = document.querySelector(descriptionSelector) as HTMLElement;
return detailsPanel && detailsPanel.innerHTML.includes(jobId) &&
description && description.innerText.length > 0;
},
jobId,
selectors.detailsPanel,
selectors.description,
);
if (loaded) {
return { success: true };
}
await sleep(pollingTime);
elapsed += pollingTime;
}
}
catch (err) {}
return {
success: false,
error: `Timeout on loading job details`
};
};
/**
* Try to paginate
* @param {Page} page
* @param {string} tag
* @param {string} paginationSize
* @param {number} timeout
* @returns {Promise<ILoadResult>}
* @static
* @private
*/
private static _paginate = async (
page: Page,
tag: string,
paginationSize: number = 25,
timeout: number = 2000,
): Promise<ILoadResult> => {
const url = new URL(page.url());
// Extract offset from url
let offset = parseInt(url.searchParams.get('start') || "0", 10);
offset += paginationSize;
// Update offset in url
url.searchParams.set('start', '' + offset);
logger.info(tag, 'Next offset: ', offset);
logger.info(tag, 'Opening', url.toString());
// Navigate new url
await page.goto(url.toString(), {
waitUntil: 'load',
});
const pollingTime = 100;
let elapsed = 0;
let loaded = false;
logger.info(tag, 'Waiting for new jobs to load');
// Wait for new jobs to load
while (!loaded) {
loaded = await page.evaluate(
(selector) => {
return document.querySelectorAll(selector).length > 0;
},
selectors.jobs,
);
if (loaded) return { success: true };
await sleep(pollingTime);
elapsed += pollingTime;
if (elapsed >= timeout) {
return {
success: false,
error: `Timeout on pagination`
};
}
}
return { success: true };
};
/**
* Hide chat panel
* @param {Page} page
* @param {string} tag
*/
private static _hideChatPanel = async (
page: Page,
tag: string,
): Promise<void> => {
try {
await page.evaluate((selector) => {
const div = document.querySelector(selector) as HTMLElement;
if (div) {
div.style.display = "none";
}
},
selectors.chatPanel);
}
catch (err) {
logger.debug(tag, "Failed to hide chat panel");
}
};
/**
* Accept cookies
* @param {Page} page
* @param {string} tag
*/
private static _acceptCookies = async (
page: Page,
tag: string,
): Promise<void> => {
try {
await page.evaluate(() => {
const buttons = Array.from(document.querySelectorAll('button'));
const cookieButton = buttons.find(e => e.innerText.includes('Accept cookies'));
if (cookieButton) {
cookieButton.click();
}
});
}
catch (err) {
logger.debug(tag, "Failed to accept cookies");
}
};
/**
* Accept privacy
* @param page
* @param tag
*/
private static _acceptPrivacy = async (
page: Page,
tag: string,
): Promise<void> => {
try {
await page.evaluate((selector) => {
const privacyButton = Array.from(document.querySelectorAll<HTMLElement>(selector))
.find(e => e.innerText === 'Accept');
if (privacyButton) {
privacyButton.click();
}
}, selectors.privacyAcceptBtn);
}
catch (err) {
logger.debug(tag, "Failed to accept privacy");
}
};
/**
* Try extracting apply link
* @param {Page} page
* @param {CDPSession} cdpSession
* @param {string} tag
* @param {number} timeout
* @returns {Promise<{ success: boolean, url?: string, error?: string | Error }>}
*/
private static _extractApplyLink = async (
page: Page,
cdpSession: CDPSession,
tag: string,
timeout = 4,
): Promise<{ success: boolean, url?: string, error?: string | Error }> => {
try {
logger.debug(tag, 'Try extracting apply link');
const currentUrl = page.url();
const elapsed = 0;
const sleepTimeMs = 100;
if (await page.evaluate((applyBtnSelector: string) => {
const applyBtn = document.querySelector(applyBtnSelector) as HTMLButtonElement;
if (applyBtn) {
applyBtn.click();
return true;
}
return false;
}, selectors.applyBtn)) {
while (elapsed < timeout) {
const targetsResponse = await cdpSession.send('Target.getTargets');
// The first target of type page with a valid url different from main page should be our guy
if (targetsResponse.targetInfos && targetsResponse.targetInfos.length > 1) {
for (const targetInfo of targetsResponse.targetInfos) {
if (targetInfo.attached && targetInfo.type === 'page' && targetInfo.url && targetInfo.url !== currentUrl) {
await cdpSession.send('Target.closeTarget', { targetId: targetInfo.targetId });
return { success: true, url: targetInfo.url };
}
}
}
await sleep(sleepTimeMs);
}
return { success: false, error: 'timeout' };
}
else {
return { success: false, error: 'apply button not found' };
}
}
catch (err: any) {
logger.warn(tag, 'Failed to extract apply link', err);
return { success: false, error: err };
}
};
/**
* Run strategy
* @param browser
* @param page
* @param cdpSession
* @param url
* @param query
* @param location
*/
public run = async (
browser: BrowserContext,
page: Page,
cdpSession: CDPSession,
url: string,
query: IQuery,
location: string,
): Promise<IRunStrategyResult> => {
let tag = `[${query.query}][${location}]`;
const metrics: IMetrics = {
processed: 0,
failed: 0,
missed: 0,
skipped: 0,
};
let paginationIndex = 0;
let paginationSize = 25;
// Navigate to home page
logger.debug(tag, "Opening", urls.home);
await page.goto(urls.home, {
waitUntil: 'load',
});
// Set cookie
logger.info("Setting authentication cookie");
await page.setCookie({
name: "li_at",
value: config.LI_AT_COOKIE!,
domain: ".www.linkedin.com"
});
// Open search url
logger.info(tag, "Opening", url);
await page.goto(url, {
waitUntil: 'load',
});
// Verify session
if (!(await AuthenticatedStrategy._isAuthenticatedSession(page))) {
logger.error("The provided session cookie is invalid. Check the documentation on how to obtain a valid session cookie.");
this.scraper.emit(events.scraper.invalidSession);
return { exit: true };
}
try {
await page.waitForSelector(selectors.container, { timeout: 5000 });
}
catch(err: any) {
logger.info(tag, `No jobs found, skip`);
return { exit: false };
}
// Pagination loop
while (metrics.processed < query.options!.limit!) {
// Verify session in the loop
if (!(await AuthenticatedStrategy._isAuthenticatedSession(page))) {
logger.warn(tag, "Session is invalid, this may cause the scraper to fail.");
this.scraper.emit(events.scraper.invalidSession);
}
else {
logger.info(tag, "Session is valid");
}
await AuthenticatedStrategy._hideChatPanel(page, tag);
await AuthenticatedStrategy._acceptCookies(page, tag);
await AuthenticatedStrategy._acceptPrivacy(page, tag);
let jobIndex = 0;
// Get number of all job links in the page
let jobsTot = await page.evaluate(
(selector) => document.querySelectorAll(selector).length,
selectors.jobs
);
if (jobsTot === 0) {
logger.info(tag, `No jobs found, skip`);
break;
}
// Jobs loop
while (jobIndex < jobsTot && metrics.processed < query.options!.limit!) {
tag = `[${query.query}][${location}][${paginationIndex * paginationSize + jobIndex + 1}]`;
let jobId;
let jobLink;
let jobApplyLink;
let jobTitle;
let jobCompany;
let jobCompanyLink;
let jobCompanyImgLink;
let jobPlace;
let jobDescription;
let jobDescriptionHTML;
let jobDate;
let loadDetailsResult;
let jobInsights;
let jobIsPromoted = false;
try {
// Extract job main fields
logger.debug(tag, 'Evaluating selectors', [
selectors.jobs,
selectors.link,
selectors.company,
selectors.place,
selectors.date,
]);
const jobFieldsResult = await page.evaluate(
(
jobsSelector: string,
linkSelector: string,
titleSelector: string,
companyLinkSelector: string,
placeSelector: string,
dateSelector: string,
jobIndex: number
) => {
const job = document.querySelectorAll(jobsSelector)[jobIndex];
const link = job.querySelector(linkSelector) as HTMLElement;
// Click job link and scroll
link.scrollIntoView();
link.click();
// Extract job link (relative)
const protocol = window.location.protocol + "//";
const hostname = window.location.hostname;
const jobLink = protocol + hostname + link.getAttribute("href");
const jobId = job.getAttribute("data-job-id");
const title = job.querySelector(titleSelector) ?
(<HTMLElement>job.querySelector(titleSelector)).innerText : "";
let company = "";
let companyLink = undefined;
if (job.querySelector(companyLinkSelector)) {
const companyLinkElem = job.querySelector(companyLinkSelector) as HTMLElement;
company = companyLinkElem.innerText.trim();
companyLink = companyLinkElem.getAttribute("href") ?
`${protocol}${hostname}${companyLinkElem.getAttribute("href")}` : undefined;
}
const companyImgLink = (<HTMLElement>job.querySelector("img"))?.getAttribute("src") ?? undefined;
const place = job.querySelector(placeSelector) ?
(<HTMLElement>job.querySelector(placeSelector)).innerText : "";
const date = job.querySelector(dateSelector) ?
(<HTMLElement>job.querySelector(dateSelector)).getAttribute('datetime') : "";
const isPromoted = !!(Array.from(job.querySelectorAll('li'))
.find(e => e.innerText === 'Promoted'));
return {
jobId,
jobLink,
title,
company,
companyLink,
companyImgLink,
place,
date,
isPromoted,
};
},
selectors.jobs,
selectors.link,
selectors.title,
selectors.companyLink,
selectors.place,
selectors.date,
jobIndex
);
jobId = jobFieldsResult.jobId;
jobLink = jobFieldsResult.jobLink;
jobTitle = jobFieldsResult.title;
jobCompany = jobFieldsResult.company;
jobCompanyLink = jobFieldsResult.companyLink;
jobCompanyImgLink = jobFieldsResult.companyImgLink;
jobPlace = jobFieldsResult.place;
jobDate = jobFieldsResult.date;
jobIsPromoted = jobFieldsResult.isPromoted;
// Promoted job
if (query.options?.skipPromotedJobs && jobIsPromoted) {
logger.info(tag, 'Skipped because promoted');
metrics.skipped += 1;
jobIndex += 1;
if (metrics.processed < query.options!.limit! && jobIndex === jobsTot && jobsTot < paginationSize) {
const loadJobsResult = await AuthenticatedStrategy._loadJobs(page, jobsTot);
if (loadJobsResult.success) {
jobsTot = loadJobsResult.count;
}
}
if (jobIndex === jobsTot) {
break;
}
else {
continue;
}
}
// Try to load job details and extract job link
logger.debug(tag, 'Evaluating selectors', [
selectors.jobs,
]);
loadDetailsResult = await AuthenticatedStrategy._loadJobDetails(page, jobId!);
// Check if loading job details has failed
if (!loadDetailsResult.success) {
logger.error(tag, loadDetailsResult.error);
jobIndex += 1;
continue;
}
// Use custom description function if available
logger.debug(tag, 'Evaluating selectors', [
selectors.description,
]);
if (query.options?.descriptionFn) {
[jobDescription, jobDescriptionHTML] = await Promise.all([
page.evaluate(`(${query.options.descriptionFn.toString()})();`),
page.evaluate((selector) => {
return (<HTMLElement>document.querySelector(selector)).outerHTML;
}, selectors.description)
]);
}
else {
[jobDescription, jobDescriptionHTML] = await page.evaluate((selector) => {
const el = (<HTMLElement>document.querySelector(selector));
return [el.innerText, el.outerHTML];
},
selectors.description
);
}
jobDescription = jobDescription as string;
// Extract job insights
logger.debug(tag, 'Evaluating selectors', [
selectors.insights,
]);
jobInsights = await page.evaluate((jobInsightsSelector: string) => {
const nodes = document.querySelectorAll(jobInsightsSelector);
return Array.from(nodes).map(e => e.textContent!
.replace(/[\n\r\t ]+/g, ' ').trim());
}, selectors.insights);
// Apply link
if (query.options?.applyLink) {
const applyLinkRes = await AuthenticatedStrategy._extractApplyLink(page, cdpSession, tag);
if (applyLinkRes.success) {
jobApplyLink = applyLinkRes.url as string;
}
}
}
catch(err: any) {
const errorMessage = `${tag}\t${err.message}`;
this.scraper.emit(events.scraper.error, errorMessage);
jobIndex++;
metrics.failed++;
continue;
}
// Emit data (NB: should be outside of try/catch block to be properly tested)
this.scraper.emit(events.scraper.data, {
query: query.query || "",
location: location,
jobId: jobId!,
jobIndex: jobIndex,
link: jobLink!,
applyLink: jobApplyLink,
title: normalizeString(jobTitle!),
company: normalizeString(jobCompany!),
companyLink: jobCompanyLink,
companyImgLink: jobCompanyImgLink,
place: normalizeString(jobPlace!),
description: jobDescription! as string,
descriptionHTML: jobDescriptionHTML! as string,
date: jobDate!,
insights: jobInsights,
});
jobIndex += 1;
metrics.processed += 1;
logger.info(tag, `Processed`);
// Try fetching more jobs
if (metrics.processed < query.options!.limit! && jobIndex === jobsTot && jobsTot < paginationSize) {
const loadJobsResult = await AuthenticatedStrategy._loadJobs(page, jobsTot);
if (loadJobsResult.success) {
jobsTot = loadJobsResult.count;
}
}
if (jobIndex === jobsTot) {
break;
}
}
tag = `[${query.query}][${location}]`;
logger.info(tag, 'No more jobs to process in this page');
// Check if we reached the limit of jobs to process
if (metrics.processed === query.options!.limit!) {
logger.info(tag, 'Query limit reached!')
// Emit metrics
this.scraper.emit(events.scraper.metrics, metrics);
logger.info(tag, 'Metrics:', metrics);
break;
}
else {
metrics.missed += paginationSize - jobIndex;
}
// Emit metrics
this.scraper.emit(events.scraper.metrics, metrics);
logger.info(tag, 'Metrics:', metrics);
// Try to paginate
paginationIndex += 1;
logger.info(tag, `Pagination requested [${paginationIndex}]`);
const paginationResult = await AuthenticatedStrategy._paginate(page, tag);
if (!paginationResult.success) {
logger.info(tag, `Couldn\'t find more jobs for the running query`);
break;
}
}
return { exit: false };
}
}