-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoJobApplierLinkedIn.py
849 lines (720 loc) · 44 KB
/
autoJobApplierLinkedIn.py
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
'''
Author: Sai Vignesh Golla
LinkedIn: https://www.linkedin.com/in/saivigneshgolla/
Copyright (C) 2024 Sai Vignesh Golla
License: GNU Affero General Public License
https://www.gnu.org/licenses/agpl-3.0.en.html
GitHub: https://github.com/GodsScion/Auto_job_applier_linkedIn
'''
# Imports
import os
import csv
import re
import pyautogui
pyautogui.FAILSAFE = False
from random import choice, shuffle, randint
from datetime import datetime
from modules.open_chrome import *
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException, NoSuchWindowException
from setup.config import *
from modules.helpers import *
from modules.clickers_and_finders import *
from modules.validator import validate_config
if use_resume_generator: from resume_generator import is_logged_in_GPT, login_GPT, open_resume_chat, create_custom_resume
#< Global Variables and logics
if run_in_background == True:
pause_at_failed_question = False
pause_before_submit = False
run_non_stop = False
first_name = first_name.strip()
middle_name = middle_name.strip()
last_name = last_name.strip()
full_name = first_name + " " + middle_name + " " + last_name if middle_name else first_name + " " + last_name
useNewResume = True
randomly_answered_questions = set()
tabs_count = 1
easy_applied_count = 0
external_jobs_count = 0
failed_count = 0
skip_count = 0
re_experience = re.compile(r'[(]?\s*(\d+)\s*[)]?\s*[-to]*\s*\d*[+]*\s*year[s]?', re.IGNORECASE)
#>
#< Login Functions
# Function to check if user is logged-in in LinkedIn
def is_logged_in_LN():
if driver.current_url == "https://www.linkedin.com/feed/": return True
if try_linkText(driver, "Sign in"): return False
if try_xp(driver, '//button[@type="submit" and contains(text(), "Sign in")]'): return False
if try_linkText(driver, "Join now"): return False
print_lg("Didn't find Sign in link, so assuming user is logged in!")
return True
# Function to login for LinkedIn
def login_LN():
# Find the username and password fields and fill them with user credentials
driver.get("https://www.linkedin.com/login")
try:
wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Forgot password?")))
try:
text_input_by_ID(driver, "username", username, 1)
except Exception as e:
print_lg("Couldn't find username field.")
# print_lg(e)
try:
text_input_by_ID(driver, "password", password, 1)
except Exception as e:
print_lg("Couldn't find password field.")
# print_lg(e)
# Find the login submit button and click it
driver.find_element(By.XPATH, '//button[@type="submit" and contains(text(), "Sign in")]').click()
except Exception as e1:
try:
profile_button = find_by_class(driver, "profile__details")
profile_button.click()
except Exception as e2:
# print_lg(e1, e2)
print_lg("Couldn't Login!")
try:
# Wait until successful redirect, indicating successful login
wait.until(EC.url_to_be("https://www.linkedin.com/feed/")) # wait.until(EC.presence_of_element_located((By.XPATH, '//button[normalize-space(.)="Start a post"]')))
return print_lg("Login successful!")
except Exception as e:
print_lg("Seems like login attempt failed! Possibly due to wrong credentials or already logged in! Try logging in manually!")
# print_lg(e)
manual_login_retry(is_logged_in_LN, 2)
#>
# Function to get list of applied job's Job IDs
def get_applied_job_ids():
job_ids = set()
try:
with open(file_name, 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
job_ids.add(row[0])
except FileNotFoundError:
print_lg(f"The CSV file '{file_name}' does not exist.")
return job_ids
# Function to apply job search filters
def apply_filters():
try:
recommended_wait = 1 if click_gap < 1 else 0
wait.until(EC.presence_of_element_located((By.XPATH, '//button[normalize-space()="All filters"]'))).click()
buffer(recommended_wait)
wait_span_click(driver, sort_by)
wait_span_click(driver, date_posted)
buffer(recommended_wait)
multi_sel(driver, experience_level)
multi_sel_noWait(driver, companies, actions)
if experience_level or companies: buffer(recommended_wait)
multi_sel(driver, job_type)
multi_sel(driver, on_site)
if job_type or on_site: buffer(recommended_wait)
if easy_apply_only: boolean_button_click(driver, actions, "Easy Apply")
multi_sel_noWait(driver, location)
multi_sel_noWait(driver, industry)
if location or industry: buffer(recommended_wait)
multi_sel_noWait(driver, job_function)
multi_sel_noWait(driver, job_titles)
if job_function or job_titles: buffer(recommended_wait)
if under_10_applicants: boolean_button_click(driver, actions, "Under 10 applicants")
if in_your_network: boolean_button_click(driver, actions, "In your network")
if fair_chance_employer: boolean_button_click(driver, actions, "Fair Chance Employer")
wait_span_click(driver, salary)
buffer(recommended_wait)
multi_sel_noWait(driver, benefits)
multi_sel_noWait(driver, commitments)
if benefits or commitments: buffer(recommended_wait)
show_results_button = driver.find_element(By.XPATH, '//button[contains(@aria-label, "Apply current filters to show")]')
show_results_button.click()
except Exception as e:
print_lg("Setting the preferences failed!")
# print_lg(e)
# Function to get pagination element and current page number
def get_page_info():
try:
pagination_element = find_by_class(driver, "artdeco-pagination")
scroll_to_view(driver, pagination_element)
current_page = int(pagination_element.find_element(By.XPATH, "//li[contains(@class, 'active')]").text)
except Exception as e:
print_lg("Failed to find Pagination element, hence couldn't scroll till end!")
pagination_element = None
current_page = None
# print_lg(e)
return pagination_element, current_page
# Function to get job main details
def get_job_main_details(job):
job_details_button = job.find_element(By.CLASS_NAME, "job-card-list__title")
scroll_to_view(driver, job_details_button, True)
title = job_details_button.text
company = job.find_element(By.CLASS_NAME, "job-card-container__primary-description").text
job_id = job.get_dom_attribute('data-occludable-job-id')
work_location = job.find_element(By.CLASS_NAME, "job-card-container__metadata-item").text
work_style = work_location[work_location.rfind('(')+1:work_location.rfind(')')]
work_location = work_location[:work_location.rfind('(')].strip()
try: job_details_button.click()
except Exception as e:
print_lg(f'Failed to click "{title} | {company}" job on details button. Job ID: {job_id}!')
# print_lg(e)
discard_job()
job_details_button.click()
buffer(click_gap)
return (job_id,title,company,work_location,work_style)
# Function to check for Blacklisted words in About Company
def check_blacklist(rejected_jobs,job_id,company,blacklisted_companies):
jobs_top_card = try_find_by_classes(driver, ["job-details-jobs-unified-top-card__primary-description-container","job-details-jobs-unified-top-card__primary-description","jobs-unified-top-card__primary-description","jobs-details__main-content"])
about_company_org = find_by_class(driver, "jobs-company__box")
scroll_to_view(driver, about_company_org)
about_company_org = about_company_org.text
about_company = about_company_org.lower()
skip_checking = False
for word in about_company_good_words:
if word.lower() in about_company:
print_lg(f'Found the word "{word}". So, skipped checking for blacklist words.')
skip_checking = True
break
if not skip_checking:
for word in about_company_bad_words:
if word.lower() in about_company:
rejected_jobs.add(job_id)
blacklisted_companies.add(company)
raise ValueError(f'\n"{about_company_org}"\n\nContains "{word}".')
buffer(click_gap)
scroll_to_view(driver, jobs_top_card)
return rejected_jobs, blacklisted_companies, jobs_top_card
# Function to extract years of experience required from About Job
def extract_years_of_experience(text):
# Extract all patterns like '10+ years', '5 years', '3-5 years', etc.
matches = re.findall(re_experience, text)
if len(matches) == 0:
print_lg(f'\n{text}\n\nCouldn\'t find experience requirement in About the Job!')
return 0
return max([int(match) for match in matches if int(match) <= 12])
# Function to upload resume
def upload_resume(modal, resume):
try:
modal.find_element(By.NAME, "file").send_keys(os.path.abspath(resume))
return True, os.path.basename(default_resume_path)
except: return False, "Previous resume"
# Function to answer common questions for Easy Apply
def answer_common_questions(label, answer):
if 'sponsorship' in label or 'visa' in label: answer = require_visa
return answer
# Function to answer the questions for Easy Apply
def answer_questions(questions_list, work_location):
# Get all questions from the page
all_questions = driver.find_elements(By.CLASS_NAME, "jobs-easy-apply-form-element")
for Question in all_questions:
# Check if it's a select Question
select = try_xp(Question, ".//select", False)
if select:
label = Question.find_element(By.TAG_NAME, "label")
label_org = label.find_element(By.TAG_NAME, "span")
label_org = label_org.text if label_org else "Unknown"
answer = 'Yes'
label = label_org.lower()
select = Select(select)
selected_option = select.first_selected_option.text
options = "".join([f' "{option.text}",' for option in select.options]) if label != "phone country code" else '"List of phone country codes"'
prev_answer = selected_option
if overwrite_previous_answers or selected_option == "Select an option":
if 'email' in label or 'phone' in label: answer = prev_answer
elif 'gender' in label or 'sex' in label: answer = gender
elif 'disability' in label: answer = disability_status
elif 'proficiency' in label: answer = 'Professional'
else: answer = answer_common_questions(label,answer)
try: select.select_by_visible_text(answer)
except NoSuchElementException as e:
''' <<<<<<<<<<<<<<<<<<
Only works if options match exactly, implement logic to check if word in options...
Also implement US voluntary self- identification
'''
print_lg(f'Failed to find an option with text "{answer}" for question labelled "{label_org}", answering randomly!')
select.select_by_index(randint(1, len(select.options)-1))
randomly_answered_questions.add((f'{label_org} [ {options} ]',"select"))
questions_list.add((f'{label_org} [ {options} ]', select.first_selected_option.text, "select", prev_answer))
continue
# Check if it's a radio Question
radio = try_xp(Question, './/fieldset[@data-test-form-builder-radio-button-form-component="true"]', False)
if radio:
prev_answer = None
label = try_xp(radio, './/span[@data-test-form-builder-radio-button-form-component__title]', False)
label = find_by_class(label, "visually-hidden", 2.0).text
label_org = label if label else "Unknown"
answer = 'Yes'
label = label_org.lower()
label_org += ' [ '
options = radio.find_elements(By.TAG_NAME, 'input')
options_labels = []
for option in options:
id = option.get_attribute("id")
option_label = try_xp(radio, f'.//label[@for="{id}"]', False)
options_labels.append( f'"{option_label.text if option_label else "Unknown"}"<{option.get_attribute("value")}>' ) # Saving option as "label <value>"
if option.is_selected(): prev_answer = options_labels[-1]
label_org += f' {options_labels[-1]},'
if overwrite_previous_answers or prev_answer is None:
if 'citizenship' in label or 'employment eligibility' in label: answer = us_citizenship
elif 'veteran' in label or 'protected' in label: answer = veteran_status
else: answer = answer_common_questions(label,answer)
if not try_xp(radio, f".//label[normalize-space()='{answer}']"):
answer = options_labels[0]
options[0].click()
randomly_answered_questions.add((f'{label_org} ]',"radio"))
else: answer = prev_answer
questions_list.add((label_org+" ]", answer, "radio", prev_answer))
continue
# Check if it's a text question
text = try_xp(Question, ".//input[@type='text']", False)
if text:
do_actions = False
label = try_xp(Question, ".//label[@for]", False)
try: label = label.find_element(By.CLASS_NAME,'visually-hidden').text
except: label = label.text
label_org = label if label else "Unknown"
answer = "" # years_of_experience
label = label_org.lower()
prev_answer = text.get_attribute("value")
if not prev_answer or overwrite_previous_answers:
if 'experience' in label or 'years' in label: answer = years_of_experience
elif 'phone' in label or 'mobile' in label: answer = phone_number
elif 'city' in label or 'location' in label or 'address' in label:
answer = current_city if current_city else work_location
do_actions = True
elif 'signature' in label: answer = full_name # 'signature' in label or 'legal name' in label or 'your name' in label or 'full name' in label: answer = full_name # What if question is 'name of the city or university you attend, name of referral etc?'
elif 'name' in label:
if 'full' in label: answer = full_name
elif 'first' in label and 'last' not in label: answer = first_name
elif 'middle' in label and 'last' not in label: answer = middle_name
elif 'last' in label and 'first' not in label: answer = last_name
else: answer = full_name
elif 'website' in label or 'blog' in label or 'portfolio' in label: answer = website
elif 'salary' in label or 'compensation' in label: answer = desired_salary
elif 'scale of 1-10' in label: answer = confidence_level
elif 'headline' in label: answer = headline
elif ('hear' in label or 'come across' in label) and 'this' in label and ('job' in label or 'position' in label): answer = "LinkedIn"
else: answer = answer_common_questions(label,answer)
if answer == "":
randomly_answered_questions.add((label_org, "text"))
answer = years_of_experience
text.clear()
text.send_keys(answer)
if do_actions:
sleep(2)
actions.send_keys(Keys.ARROW_DOWN)
actions.send_keys(Keys.ENTER).perform()
questions_list.add((label, text.get_attribute("value"), "text", prev_answer))
continue
# Check if it's a textarea question
text_area = try_xp(Question, ".//textarea", False)
if text_area:
label = try_xp(Question, ".//label[@for]", False)
label_org = label.text if label else "Unknown"
label = label_org.lower()
answer = ""
prev_answer = text_area.get_attribute("value")
if not prev_answer or overwrite_previous_answers:
if 'summary' in label: answer = summary
elif 'cover' in label: answer = cover_letter
text_area.clear()
text_area.send_keys(answer)
if answer == "":
randomly_answered_questions.add((label_org, "textarea"))
questions_list.add((label, text_area.get_attribute("value"), "textarea", prev_answer))
continue
# Check if it's a checkbox question
checkbox = try_xp(Question, ".//input[@type='checkbox']", False)
if checkbox:
label = try_xp(Question, ".//span[@class='visually-hidden']", False)
label_org = label.text if label else "Unknown"
label = label_org.lower()
answer = try_xp(Question, ".//label[@for]", False).text
prev_answer = checkbox.is_selected()
if not prev_answer: checkbox.click()
questions_list.add((f'{label} ([X] {answer})', checkbox.is_selected(), "checkbox", prev_answer))
continue
# Select todays date
try_xp(driver, "//button[contains(@aria-label, 'This is today')]")
# Collect important skills
# if 'do you have' in label and 'experience' in label and ' in ' in label -> Get word (skill) after ' in ' from label
# if 'how many years of experience do you have in ' in label -> Get word (skill) after ' in '
return questions_list
# Function to open new tab and save external job application links
def external_apply(pagination_element, job_id, job_link, resume, date_listed, application_link, screenshot_name):
global tabs_count
if easy_apply_only:
print_lg("Easy apply failed I guess!")
if pagination_element != None: return True, application_link, tabs_count
try:
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(span, "Apply") and not(span[contains(@class, "disabled")])]'))).click()
windows = driver.window_handles
tabs_count = len(windows)
driver.switch_to.window(windows[-1])
application_link = driver.current_url
print_lg('Got the external application link "{}"'.format(application_link))
if close_tabs: driver.close()
driver.switch_to.window(linkedIn_tab)
return False, application_link, tabs_count
except Exception as e:
# print_lg(e)
print_lg("Failed to apply!")
failed_job(job_id, job_link, resume, date_listed, "Probably didn't find Apply button or unable to switch tabs.", e, application_link, screenshot_name)
global failed_count
failed_count += 1
return True, application_link, tabs_count
#< Failed attempts logging
# Function to update failed jobs list in excel
def failed_job(job_id, job_link, resume, date_listed, error, exception, application_link, screenshot_name):
with open(failed_file_name, 'a', newline='', encoding='utf-8') as file:
fieldnames = ['Job ID', 'Job Link', 'Resume Tried', 'Date listed', 'Date Tried', 'Assumed Reason', 'Stack Trace', 'External Job link', 'Screenshot Name']
writer = csv.DictWriter(file, fieldnames=fieldnames)
if file.tell() == 0: writer.writeheader()
writer.writerow({'Job ID':job_id, 'Job Link':job_link, 'Resume Tried':resume, 'Date listed':date_listed, 'Date Tried':datetime.now(), 'Assumed Reason':error, 'Stack Trace':exception, 'External Job link':application_link, 'Screenshot Name':screenshot_name})
file.close()
# Function to to take screenshot for debugging
def screenshot(driver, job_id, failedAt):
screenshot_name = "{} - {} - {}.png".format( job_id, failedAt, str(datetime.now()) )
path = logs_folder_path+"/screenshots/"+screenshot_name.replace(":",".")
# special_chars = {'*', '"', '\\', '<', '>', ':', '|', '?'}
# for char in special_chars: path = path.replace(char, '-')
driver.save_screenshot(path.replace("//","/"))
return screenshot_name
#>
# Function to create or append to the CSV file, once the application is submitted successfully
def submitted_jobs(job_id, title, company, work_location, work_style, description, experience_required, skills, hr_name, hr_link, resume, reposted, date_listed, date_applied, job_link, application_link, questions_list, connect_request):
with open(file_name, mode='a', newline='', encoding='utf-8') as csv_file:
fieldnames = ['Job ID', 'Title', 'Company', 'Work Location', 'Work Style', 'About Job', 'Experience required', 'Skills required', 'HR Name', 'HR Link', 'Resume', 'Re-posted', 'Date Posted', 'Date Applied', 'Job Link', 'External Job link', 'Questions Found', 'Connect Request']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if csv_file.tell() == 0: writer.writeheader()
writer.writerow({'Job ID':job_id, 'Title':title, 'Company':company, 'Work Location':work_location, 'Work Style':work_style,
'About Job':description, 'Experience required': experience_required, 'Skills required':skills,
'HR Name':hr_name, 'HR Link':hr_link, 'Resume':resume, 'Re-posted':reposted,
'Date Posted':date_listed, 'Date Applied':date_applied, 'Job Link':job_link,
'External Job link':application_link, 'Questions Found':questions_list, 'Connect Request':connect_request})
csv_file.close()
# Function to discard the job application
def discard_job():
actions.send_keys(Keys.ESCAPE).perform()
wait_span_click(driver, 'Discard', 2)
# Function to apply to jobs
def apply_to_jobs(search_terms):
applied_jobs = get_applied_job_ids()
rejected_jobs = set()
blacklisted_companies = set()
global current_city, failed_count, skip_count, easy_applied_count, external_jobs_count, tabs_count, pause_before_submit, pause_at_failed_question, useNewResume
current_city = current_city.strip()
if randomize_search_order: shuffle(search_terms)
for searchTerm in search_terms:
driver.get(f"https://www.linkedin.com/jobs/search/?keywords={searchTerm}")
print_lg("\n________________________________________________________________________________________________________________________\n")
print_lg(f'\n>>>> Now searching for "{searchTerm}" <<<<\n\n')
if search_location.strip():
print_lg(f'Setting search location as: "{search_location.strip()}"')
search_location_ele = try_xp(driver, "//input[@aria-label='City, state, or zip code'and not(@disabled)]", False) # and not(@aria-hidden='true')]")
search_location_ele.clear()
search_location_ele.send_keys(search_location.strip())
sleep(2)
actions.send_keys(Keys.ENTER).perform()
apply_filters()
current_count = 0
try:
while current_count < switch_number:
# Wait until job listings are loaded
wait.until(EC.presence_of_all_elements_located((By.XPATH, "//li[contains(@class, 'jobs-search-results__list-item')]")))
pagination_element, current_page = get_page_info()
# Find all job listings in current page
buffer(3)
job_listings = driver.find_elements(By.CLASS_NAME, "jobs-search-results__list-item")
for job in job_listings:
if keep_screen_awake: pyautogui.press('shiftright')
if current_count >= switch_number: break
print_lg("\n-@-\n")
job_id,title,company,work_location,work_style = get_job_main_details(job)
# Skip if previously rejected due to blacklist or already applied
if company in blacklisted_companies:
print_lg(f'Skipping "{title} | {company}" job (Blacklisted Company). Job ID: {job_id}!')
continue
elif job_id in rejected_jobs:
print_lg(f'Skipping previously rejected "{title} | {company}" job. Job ID: {job_id}!')
continue
try:
if job_id in applied_jobs or find_by_class(driver, "jobs-s-apply__application-link", 2):
print_lg(f'Already applied to "{title} | {company}" job. Job ID: {job_id}!')
continue
except Exception as e:
print_lg(f'Trying to Apply to "{title} | {company}" job. Job ID: {job_id}')
job_link = "https://www.linkedin.com/jobs/view/"+job_id
application_link = "Easy Applied"
date_applied = "Pending"
hr_link = "Unknown"
hr_name = "Unknown"
connect_request = "In Development" # Still in development
date_listed = "Unknown"
description = "Unknown"
experience_required = "Unknown"
skills = "In Development" # Still in development
resume = "Pending"
reposted = False
questions_list = None
screenshot_name = "Not Available"
try:
rejected_jobs, blacklisted_companies, jobs_top_card = check_blacklist(rejected_jobs,job_id,company,blacklisted_companies)
except ValueError as e:
print_lg(e, 'Skipping this job!\n')
failed_job(job_id, job_link, resume, date_listed, "Found Blacklisted words in About Company", e, "Skipped", screenshot_name)
skip_count += 1
continue
except Exception as e:
print_lg("Failed to scroll to About Company!")
# print_lg(e)
# Hiring Manager info
try:
hr_info_card = WebDriverWait(driver,2).until(EC.presence_of_element_located((By.CLASS_NAME, "hirer-card__hirer-information")))
hr_link = hr_info_card.find_element(By.TAG_NAME, "a").get_attribute("href")
hr_name = hr_info_card.find_element(By.TAG_NAME, "span").text
# if connect_hr:
# driver.switch_to.new_window('tab')
# driver.get(hr_link)
# wait_span_click("More")
# wait_span_click("Connect")
# wait_span_click("Add a note")
# message_box = driver.find_element(By.XPATH, "//textarea")
# message_box.send_keys(connect_request_message)
# if close_tabs: driver.close()
# driver.switch_to.window(linkedIn_tab)
# def message_hr(hr_info_card):
# if not hr_info_card: return False
# hr_info_card.find_element(By.XPATH, ".//span[normalize-space()='Message']").click()
# message_box = driver.find_element(By.XPATH, "//div[@aria-label='Write a message…']")
# message_box.send_keys()
# try_xp(driver, "//button[normalize-space()='Send']")
except Exception as e:
print_lg(f'HR info was not given for "{title}" with Job ID: {job_id}!')
# print_lg(e)
# Calculation of date posted
try:
# try: time_posted_text = find_by_class(driver, "jobs-unified-top-card__posted-date", 2).text
# except:
time_posted_text = jobs_top_card.find_element(By.XPATH, './/span[contains(normalize-space(), " ago")]').text
print("Time Posted: " + time_posted_text)
if time_posted_text.__contains__("Reposted"):
reposted = True
time_posted_text = time_posted_text.replace("Reposted", "")
date_listed = calculate_date_posted(time_posted_text)
except Exception as e:
print_lg("Failed to calculate the date posted!",e)
# Get job description
try:
found_masters = 0
description = find_by_class(driver, "jobs-box__html-content").text
descriptionLow = description.lower()
skip = False
for word in bad_words:
if word.lower() in descriptionLow:
message = f'\n{description}\n\nContains bad word "{word}". Skipping this job!\n'
reason = "Found a Bad Word in About Job"
skip = True
break
if not skip and security_clearance == False and ('polygraph' in descriptionLow or 'clearance' in descriptionLow or 'secret' in descriptionLow):
message = f'\n{description}\n\nFound "Clearance" or "Polygraph". Skipping this job!\n'
reason = "Asking for Security clearance"
skip = True
if not skip:
if did_masters and 'master' in descriptionLow:
print_lg(f'Found the word "master" in \n{description}')
found_masters = 2
experience_required = extract_years_of_experience(description)
if current_experience > -1 and experience_required > current_experience + found_masters:
message = f'\n{description}\n\nExperience required {experience_required} > Current Experience {current_experience + found_masters}. Skipping this job!\n'
reason = "Required experience is high"
skip = True
if skip:
print_lg(message)
failed_job(job_id, job_link, resume, date_listed, reason, message, "Skipped", screenshot_name)
rejected_jobs.add(job_id)
skip_count += 1
continue
except Exception as e:
if description == "Unknown": print_lg("Unable to extract job description!")
else:
experience_required = "Error in extraction"
print_lg("Unable to extract years of experience required!")
# print_lg(e)
uploaded = False
# Case 1: Easy Apply Button
if wait_span_click(driver, "Easy Apply", 2):
try:
try:
errored = ""
modal = find_by_class(driver, "jobs-easy-apply-modal")
wait_span_click(modal, "Next", 1)
# if description != "Unknown":
# resume = create_custom_resume(description)
resume = "Previous resume"
next_button = True
questions_list = set()
next_counter = 0
while next_button:
next_counter += 1
if next_counter >= 6:
if pause_at_failed_question:
screenshot(driver, job_id, "Needed manual intervention for failed question")
pyautogui.alert("Couldn't answer one or more questions.\nPlease click \"Continue\" once done.\nDO NOT CLICK Back, Next or Review button in LinkedIn.\n\n\n\n\nYou can turn off \"Pause at failed question\" setting in config.py", "Help Needed", "Continue")
next_counter = 1
continue
if questions_list: print_lg("Stuck for one or some of the following questions...", questions_list)
screenshot_name = screenshot(driver, job_id, "Failed at questions")
errored = "stuck"
raise Exception("Seems like stuck in a continuous loop of next, probably because of new questions.")
questions_list = answer_questions(questions_list, work_location)
if useNewResume and not uploaded: uploaded, resume = upload_resume(modal, default_resume_path)
try: next_button = modal.find_element(By.XPATH, './/span[normalize-space(.)="Review"]')
except NoSuchElementException: next_button = modal.find_element(By.XPATH, './/button[contains(span, "Next")]')
try: next_button.click()
except ElementClickInterceptedException: break # Happens when it tries to click Next button in About Company photos section
buffer(click_gap)
except NoSuchElementException: errored = "nose"
finally:
if questions_list and errored != "stuck":
print_lg("Answered the following questions...", questions_list)
print("\n\n" + "\n".join(str(question) for question in questions_list) + "\n\n")
wait_span_click(driver, "Review", 1, scrollTop=True)
cur_pause_before_submit = pause_before_submit
if errored != "stuck" and cur_pause_before_submit:
pause_before_submit = False if "Turn off" == pyautogui.confirm('1. Please verify your information.\n2. If you edited something, please return to this final screen.\n3. DO NOT CLICK "Submit Application".\n\n\n\n\nYou can turn off "Pause before submit" setting in config.py\nTo TEMPORARILY turn it off, click "Turn off"', "Confirm your information",["Turn off", "Continue"]) else True
try_xp(modal, ".//span[normalize-space(.)='Review']")
if wait_span_click(driver, "Submit application", 2, scrollTop=True):
date_applied = datetime.now()
if not wait_span_click(driver, "Done", 2): actions.send_keys(Keys.ESCAPE).perform()
elif errored != "stuck" and cur_pause_before_submit and "Yes" in pyautogui.confirm("You submitted the application, didn't you 😒?", "Failed to find Submit Application!", ["Yes", "No"]):
date_applied = datetime.now()
wait_span_click(driver, "Done", 2)
else:
print_lg("Since, Submit Application failed, discarding the job application...")
# if screenshot_name == "Not Available": screenshot_name = screenshot(driver, job_id, "Failed to click Submit application")
# else: screenshot_name = [screenshot_name, screenshot(driver, job_id, "Failed to click Submit application")]
if errored == "nose": raise Exception("Failed to click Submit application 😑")
except Exception as e:
print_lg("Failed to Easy apply!")
# print_lg(e)
critical_error_log("Somewhere in Easy Apply process",e)
failed_job(job_id, job_link, resume, date_listed, "Problem in Easy Applying", e, application_link, screenshot_name)
failed_count += 1
discard_job()
continue
else:
# Case 2: Apply externally
skip, application_link, tabs_count = external_apply(pagination_element, job_id, job_link, resume, date_listed, application_link, screenshot_name)
if skip: continue
submitted_jobs(job_id, title, company, work_location, work_style, description, experience_required, skills, hr_name, hr_link, resume, reposted, date_listed, date_applied, job_link, application_link, questions_list, connect_request)
if uploaded: useNewResume = False
print_lg(f'Successfully saved "{title} | {company}" job. Job ID: {job_id} info')
current_count += 1
if application_link == "Easy Applied": easy_applied_count += 1
else: external_jobs_count += 1
applied_jobs.add(job_id)
# Switching to next page
if pagination_element == None:
print_lg("Couldn't find pagination element, probably at the end page of results!")
break
try:
pagination_element.find_element(By.XPATH, f"//button[@aria-label='Page {current_page+1}']").click()
print_lg(f"\n>-> Now on Page {current_page+1} \n")
except NoSuchElementException:
print_lg(f"\n>-> Didn't find Page {current_page+1}. Probably at the end page of results!\n")
break
except Exception as e:
print_lg("Failed to find Job listings!")
critical_error_log("In Applier", e)
# print_lg(e)
def run(total_runs):
print_lg("\n########################################################################################################################\n")
print_lg(f"Date and Time: {datetime.now()}")
print_lg(f"Cycle number: {total_runs}")
print_lg(f"Currently looking for jobs posted within '{date_posted}' and sorting them by '{sort_by}'")
apply_to_jobs(search_terms)
print_lg("########################################################################################################################\n")
print_lg("Sleeping for 10 min...")
sleep(0)
print_lg("Few more min... Gonna start with in next 5 min...")
buffer(-3)
return total_runs + 1
chatGPT_tab = False
linkedIn_tab = False
def main():
try:
global linkedIn_tab, tabs_count, useNewResume
alert_title = "Error Occurred. Closing Browser!"
total_runs = 1
validate_config()
if not os.path.exists(default_resume_path):
pyautogui.alert(text='Your default resume "{}" is missing! Please update it\'s folder path "default_resume_path" in config.py\n\nOR\n\nAdd a resume with exact name and path (check for spelling mistakes including cases).\n\n\nFor now the bot will continue using your previous upload from LinkedIn!'.format(default_resume_path), title="Missing Resume", button="OK")
useNewResume = False
# Login to LinkedIn
tabs_count = len(driver.window_handles)
driver.get("https://www.linkedin.com/login")
if not is_logged_in_LN(): login_LN()
linkedIn_tab = driver.current_window_handle
# Login to ChatGPT in a new tab for resume customization
if use_resume_generator:
try:
driver.switch_to.new_window('tab')
driver.get("https://chat.openai.com/")
if not is_logged_in_GPT(): login_GPT()
open_resume_chat()
global chatGPT_tab
chatGPT_tab = driver.current_window_handle
except Exception as e:
print_lg("Opening OpenAI chatGPT tab failed!")
# Start applying to jobs
driver.switch_to.window(linkedIn_tab)
total_runs = run(total_runs)
while(run_non_stop):
if cycle_date_posted:
date_options = ["Any time", "Past month", "Past week", "Past 24 hours"]
global date_posted
date_posted = date_options[date_options.index(date_posted)+1 if date_options.index(date_posted)+1 > len(date_options) else -1] if stop_date_cycle_at_24hr else date_options[0 if date_options.index(date_posted)+1 >= len(date_options) else date_options.index(date_posted)+1]
if alternate_sortby:
global sort_by
sort_by = "Most recent" if sort_by == "Most relevant" else "Most relevant"
total_runs = run(total_runs)
sort_by = "Most recent" if sort_by == "Most relevant" else "Most relevant"
total_runs = run(total_runs)
except NoSuchWindowException: pass
except Exception as e:
critical_error_log("In Applier Main", e)
pyautogui.alert(e,alert_title)
finally:
print_lg("\n\nTotal runs: {}".format(total_runs))
print_lg("Jobs Easy Applied: {}".format(easy_applied_count))
print_lg("External job links collected: {}".format(external_jobs_count))
print_lg(" ----------")
print_lg("Total applied or collected: {}".format(easy_applied_count + external_jobs_count))
print_lg("\nFailed jobs: {}".format(failed_count))
print_lg("Irrelevant jobs skipped: {}\n".format(skip_count))
if randomly_answered_questions: print_lg("\n\nQuestions randomly answered:\n {} \n\n".format(";\n".join(str(question) for question in randomly_answered_questions)))
quote = choice([
"You're one step closer than before.",
"All the best with your future interviews.",
"Keep up with the progress. You got this.",
"If you're tired, learn to take rest but never give up.",
"Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill",
"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle. - Christian D. Larson",
"Every job is a self-portrait of the person who does it. Autograph your work with excellence.",
"The only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. - Steve Jobs",
"Opportunities don't happen, you create them. - Chris Grosser",
"The road to success and the road to failure are almost exactly the same. The difference is perseverance.",
"Obstacles are those frightful things you see when you take your eyes off your goal. - Henry Ford",
"The only limit to our realization of tomorrow will be our doubts of today. - Franklin D. Roosevelt"
])
msg = f"\n{quote}\n\n\nBest regards,\nSai Vignesh Golla\nhttps://www.linkedin.com/in/saivigneshgolla/\n\n"
pyautogui.alert(msg, "Exiting..")
print_lg(msg,"Closing the browser...")
if tabs_count >= 10:
msg = "NOTE: IF YOU HAVE MORE THAN 10 TABS OPENED, PLEASE CLOSE OR BOOKMARK THEM!\n\nOr it's highly likely that application will just open browser and not do anything next time!"
pyautogui.alert(msg,"Info")
print_lg("\n"+msg)
try: driver.quit()
except Exception as e: critical_error_log("When quitting...", e)
main()