-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
444 lines (390 loc) · 13.4 KB
/
index.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
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
require("dotenv").config();
const { exit } = require("process");
const puppeteer = require("puppeteer");
const fs = require("fs");
const createCsvWriter = require("csv-writer").createObjectCsvWriter;
const data = require("./config.json");
const { EMAIL: email, PASSWORD: password } = process.env;
const {
baseURL,
keyword,
workPlaceTypes,
location,
AvgExperience,
periodOfTime,
browserPath,
resolution,
numberOfPagination,
numberOfOffersPerPage,
avoidJobTitles,
avoidCompanyNames,
} = data;
let page = "";
let browser = "";
let csvWriter = null;
function logs() {
console.clear();
console.log("\n==========================================\n");
console.log("\tLinkedIn Easy Apply Bot");
console.log("\n==========================================\n");
}
async function Login() {
await findTargetAndType('[name="session_key"]', email);
await findTargetAndType('[name="session_password"]', password);
page.keyboard.press("Enter");
}
async function initializer() {
browser = await puppeteer.launch({
headless: false,
executablePath: browserPath,
args: [resolution],
defaultViewport: null,
timeout: 60000,
// userDataDir: "./userData",
});
page = await browser.newPage();
const pages = await browser.pages();
if (pages.length > 1) {
await pages[0].close();
}
await page.goto(baseURL);
csvWriter = createCsvWriter({
path: "report.csv",
header: [
{ id: "jobTitle", title: "Job Title" },
{ id: "link", title: "Link" },
{ id: "status", title: "Status" },
],
});
}
async function findTargetAndType(target, value) {
const f = await page.$(target);
await f.type(value);
}
async function waitForSelectorAndType(target, value) {
const typer = await page.waitForSelector(target, { visible: true });
await typer.type(value);
}
async function buttonClick(selector) {
try {
await page.waitForSelector(selector);
const buttonClick = await page.$(selector);
await buttonClick.click();
} catch (error) {
console.error(`Error clicking element with selector '${selector}':`, error);
}
}
const pause = async (ms=3000) => {
await new Promise(resolve => setTimeout(resolve, ms));
}
async function jobCriteriaByTime() {
await buttonClick(".search-reusables__filter-binary-toggle");
await pause();
await buttonClick(
"ul.search-reusables__filter-list>li:nth-child(4)>div>span>button"
);
if (periodOfTime == "Past 24 hours") {
// apply to the jobs posted in the last 24 hrs
await pause();
await buttonClick(
"form > fieldset > div.pl4.pr6 > ul > li:nth-child(4) > label"
);
await pause();
await buttonClick("form > fieldset > div + hr + div > button + button");
} else {
// apply to the jobs posted within the past week
await pause();
await buttonClick(
"form > fieldset > div.pl4.pr6 > ul > li:nth-child(3) > label"
);
await pause();
await buttonClick("form > fieldset > div + hr + div > button + button");
}
}
async function jobCriteriaByType() {
await buttonClick(".search-reusables__filter-list>li:nth-child(8)>div");
await pause();
await buttonClick(workPlaceTypes.remote);
await buttonClick(workPlaceTypes.hybrid);
await buttonClick(workPlaceTypes.onsite);
await pause();
await buttonClick(
".search-reusables__filter-list>li:nth-child(8)>div>div>div>div>div>form>fieldset>div+hr+div>button+button"
); // click the `show results` button
await pause();
}
async function clickElement(selector) {
try {
const element = await page.$(selector);
if (element !== null) {
await element.click();
} else {
console.error(`Element with selector '${selector}' not found.`);
}
} catch (error) {
console.error(`Error clicking element with selector '${selector}':`, error);
}
}
async function Scrolling() {
console.log("\nScrolling.....");
try {
await page.evaluate(() => {
const listOfJobs = document.querySelector(
"div.scaffold-layout__list > div > ul"
);
if (listOfJobs) {
listOfJobs.scrollIntoView();
} else {
console.error("Element not found for scrolling.");
}
});
} catch (error) {
console.error("Error scrolling:", error);
}
}
function changeValue(input, value) {
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
nativeInputValueSetter.call(input, value);
var inputEvent = new Event("input", { bubbles: true });
input.dispatchEvent(inputEvent);
}
function writeInCSV(data) {
csvWriter
.writeRecords([data]) // Write data to CSV
.then(() => {
console.log("CSV file written successfully");
})
.catch((error) => {
console.error("Error writing new entry:", error);
});
}
async function getCompanyName() {
const companyNameSelector =
".job-details-jobs-unified-top-card__company-name>a";
const companyName = await page.evaluate((selector) => {
const element = document.querySelector(selector);
return element ? element.text : null;
}, companyNameSelector);
return companyName;
}
async function getJobTitle() {
const jobTitleSelector = ".job-details-jobs-unified-top-card__job-title>h1>a";
const jobTitle = await page.evaluate((selector) => {
const element = document.querySelector(selector);
return element ? element.text : null;
}, jobTitleSelector);
return jobTitle;
}
async function getLink() {
const jobLinkSelector = ".job-details-jobs-unified-top-card__job-title>h1>a";
const jobLink = await page.evaluate((selector) => {
const element = document.querySelector(selector);
return element ? element.href : null;
}, jobLinkSelector);
return jobLink;
}
async function FillAndApply() {
let i = 1;
let lastIndexForPagination = 1;
while (i <= numberOfPagination) {
for (let index = 1; index <= numberOfOffersPerPage; index++) {
let state = true;
await Scrolling();
console.log(`Apply N°[${index}]`);
const activeJob = `[class*='jobs-search-two-pane__job-card-container--viewport-tracking-${index-1}']>div`;
if ((await page.$(activeJob)) != null) {
await buttonClick(activeJob);
}
if (index === numberOfOffersPerPage) lastIndexForPagination++;
await pause();
//Check for application button
if ((await page.$("[class*=jobs-apply-button]>button")) != null) {
let companyName = await getCompanyName();
const containsUnwantedCompanyName = avoidCompanyNames.some((name) =>
companyName?.toLowerCase().includes(name?.toLowerCase())
);
if (containsUnwantedCompanyName) {
console.log(`Skipping this job from company: ${companyName}`);
continue;
}
let jobTitle = await getJobTitle();
console.log("jobTitle: " + jobTitle);
let jobLink = await getLink();
console.log("jobLink: " + jobLink);
// Check if the job title is in the list of titles to avoid
const jobTitleRegex = new RegExp(
`\\b(${avoidJobTitles
.map((title) => title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join("|")})(?=\\b|[^a-zA-Z0-9])`,
"i"
);
if (jobTitleRegex.test(jobTitle)) {
console.log(`Skipping job with title: ${jobTitle}`);
continue;
}
console.log(`Applying to ${jobTitle} ...`);
// Click the "Easy Apply" button
await pause();
const easyApplyLimitReached = await page.evaluate(() => {
const easyApplyLimitTextIsVisible = document.querySelector(
'div[class*="mt3 artdeco-inline-feedback artdeco-inline-feedback--error ember-view"]'
);
if (easyApplyLimitTextIsVisible) return true;
const easyApplyButton = document.querySelector(
'div[class*="jobs-apply-button"]>button'
);
if (easyApplyButton) easyApplyButton.click();
});
if (easyApplyLimitReached) {
console.log(
"==========\nYou've reached the Easy Apply application limit for today. Exiting the app...\n=========="
);
exit(0);
}
// Check to see if the "Job search safety reminder" dialog comes up instead
await pause();
await page.evaluate(() => {
const continueApplyingButton = document.querySelector(
'div[class="artdeco-modal__actionbar ember-view job-trust-pre-apply-safety-tips-modal__footer"]>button+div>div>button'
);
if (continueApplyingButton) continueApplyingButton.click(); // Click the "Continue applying" button in the "Job search safety reminder" dialog
});
while (state == true) {
await pause();
if (
await page.evaluate(() => {
const nextBtn = document.querySelector(
'div[class="display-flex justify-flex-end ph5 pv4"]>button'
);
if (nextBtn) nextBtn.click(); // Click the "Next" button in the Apply dialog
})
) {
state = true;
} else {
state = false;
break;
}
await pause();
}
if (state == false) {
// TODO: add `await page.evaluate()` to the element below, test with kforce jobs or jobs that only have one page.
await clickElement(
'div[class="display-flex justify-flex-end ph5 pv4"]>button + button'
);
await pause();
if (
(await page.$(
'input[class="ember-text-field ember-view fb-single-line-text__input"]'
)) != null
) {
await page.evaluate(() => {
const divElem = document.querySelector("div.pb4");
const inputElements = divElem.querySelectorAll("input");
let value = 3;
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
for (let index = 0; index < inputElements.length; index++) {
nativeInputValueSetter.call(inputElements[index], value);
var inputEvent = new Event("input", { bubbles: true });
inputElements[index].dispatchEvent(inputEvent);
}
});
}
let counter = 0;
let finalPage = false;
do {
await pause();
const modalExists = await page.$(
'div[class*="artdeco-modal-overlay"]>div>div+div>div>button>span'
);
if (!modalExists) {
counter++;
console.log("counter: " + counter);
finalPage = await page.evaluate(() => {
const nextButton = document.querySelector(
'div[class="display-flex justify-flex-end ph5 pv4"]>button + button'
);
if (nextButton) {
nextButton.click();
return false;
} else {
return true;
}
});
} else counter = -2;
} while (counter >= 0 && counter < 20 && finalPage === false);
let skipped = false;
if (counter >= 5 && finalPage === false) {
// due to inactivity, skip the job
await pause();
await buttonClick(
".artdeco-modal__dismiss.artdeco-button.artdeco-button--circle.artdeco-button--muted.artdeco-button--2.artdeco-button--tertiary.ember-view"
);
await pause();
await buttonClick(
'[data-control-name="discard_application_confirm_btn"]'
);
skipped = true;
console.log("Job Skipped");
} else {
// Finish the job application by closing the dialog with the `X` button.
await pause();
await page.evaluate(() => {
const xBtn = document.querySelector(
".artdeco-modal__dismiss.artdeco-button.artdeco-button--circle.artdeco-button--muted.artdeco-button--2.artdeco-button--tertiary.ember-view"
);
if (xBtn) xBtn.click();
});
}
// Add the Job to the CSV file
writeInCSV({
jobTitle: jobTitle,
link: "https://www.linkedin.com" + jobLink,
status: skipped ? "Skipped" : "Applied",
});
}
}
}
await Scrolling();
await buttonClick(
`ul[class="artdeco-pagination__pages artdeco-pagination__pages--number"]>li:nth-child(${lastIndexForPagination})`
);
i++;
console.log("finished Scrolling page N°" + (i - 1));
}
}
async function jobsApply() {
await buttonClick("#global-nav > div > nav > ul > li:nth-child(3)");
await pause();
await waitForSelectorAndType(
'[id^="jobs-search-box-keyword-id"]',
keyword.join(" OR ")
);
await pause(1000);
const jobLocationSelector = '[id^="jobs-search-box-location-id"]';
await page.evaluate((selector) => {
const locationSelector = document.querySelector(selector);
if (locationSelector) locationSelector.value = "";
}, jobLocationSelector);
await waitForSelectorAndType(jobLocationSelector, location);
await page.keyboard.press("Enter");
await pause(1000);
await jobCriteriaByTime();
await pause();
await jobCriteriaByType();
await pause();
await FillAndApply();
}
async function main() {
logs();
await initializer();
await Login();
await jobsApply();
await browser.close();
}
main();