forked from wodsuz/EasyApplyJobsBot
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
linkedin.py
executable file
·680 lines (498 loc) · 29.9 KB
/
linkedin.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
import math
from typing import List
import config
import constants
import models
import repository_wrapper
import utils
import re
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from utils import prGreen, prRed, prYellow
from webdriver_manager.chrome import ChromeDriverManager
# This class is responsible for handling the LinkedIn job application process
# It uses the Selenium WebDriver to interact with the LinkedIn website
# It also uses the repository_wrapper to interact with the backend
#
# The class is responsible for:
# - Logging in to LinkedIn (done in the constructor)
# - Searching for jobs
# - Applying to jobs
# - Handling job posts
# - Handling questions
# - Handling multiple pages of the application process
# - Handling the resume selection
# - Handling the submission of the application
# - Handling the follow company checkbox
# - Handling the application of the job
class Linkedin:
def __init__(self):
prYellow("🌐 The Bot is starting.")
if config.chromeDriverPath != "":
# Specify the path to Chromedriver provided by the Alpine package
service = ChromeService(executable_path=config.chromeDriverPath)
else:
service = ChromeService(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=utils.chromeBrowserOptions())
self.wait = WebDriverWait(self.driver, 15)
# Navigate to the LinkedIn home page to check if we're already logged in
self.goToUrl("https://www.linkedin.com")
if not self.checkIfLoggedIn():
self.goToUrl("https://www.linkedin.com/login?trk=guest_homepage-basic_nav-header-signin")
prYellow("🔄 Trying to log in linkedin...")
try:
self.driver.find_element("id","username").send_keys(config.email)
utils.sleepInBetweenActions(1,2)
self.driver.find_element("id","password").send_keys(config.password)
utils.sleepInBetweenActions(1, 2)
self.driver.find_element("xpath",'//button[@type="submit"]').click()
utils.sleepInBetweenActions(3, 7)
self.checkIfLoggedIn()
except:
prRed("❌ Couldn't log in Linkedin by using Chrome. Please check your Linkedin credentials on config files line 7 and 8. If error continue you can define Chrome profile or run the bot on Firefox")
repository_wrapper.init()
def checkIfLoggedIn(self):
if self.exists(self.driver, By.CSS_SELECTOR, "img.global-nav__me-photo.evi-image.ember-view"):
prGreen("✅ Logged in Linkedin.")
return True
else:
return False
def startApplying(self):
try:
jobCounter = models.JobCounter()
urlData = utils.LinkedinUrlGenerator().generateSearchUrls()
for url in urlData:
self.goToUrl(url)
urlWords = utils.urlToKeywords(url)
try:
totalJobs = self.wait.until(EC.presence_of_element_located((By.XPATH, '//small'))).text # TODO - fix finding total jobs
# totalJobs = self.driver.find_element(By.XPATH,'//small').text
totalSearchResultPages = utils.jobsToPages(totalJobs)
lineToWrite = "\n Search keyword: " + urlWords[0] + ", Location: " + urlWords[1] + ", Found " + str(totalJobs)
self.displayWriteResults(lineToWrite)
for searchResultPage in range(totalSearchResultPages):
currentSearchResultPageJobs = constants.jobsPerPage * searchResultPage
url = url + "&start=" + str(currentSearchResultPageJobs)
self.goToUrl(url)
jobsForVerification = self.getJobsFromSearchPage()
verifiedJobs = repository_wrapper.verify_jobs(jobsForVerification)
for job in verifiedJobs:
jobCounter = self.processJob(jobID=job.linkedinJobId, jobCounter=jobCounter)
except TimeoutException:
prRed("0 jobs found for: " + urlWords[0] + " in " + urlWords[1])
prYellow("Category: " + urlWords[0] + " in " + urlWords[1]+ " applied: " + str(jobCounter.applied) +
" jobs out of " + str(jobCounter.total) + ".")
except Exception as e:
utils.logDebugMessage("Unhandled exception in startApplying", utils.MessageTypes.ERROR, e, True)
self.driver.save_screenshot("unhandled_exception.png")
with open("page_source_at_unhandled_exception.html", "w") as file:
file.write(self.driver.page_source)
def goToJobsSearchPage(self):
searchUrl = utils.LinkedinUrlGenerator.getGeneralSearchUrl()
self.goToUrl(searchUrl)
def goToEasyApplyJobsSearchPage(self):
searchUrl = utils.LinkedinUrlGenerator.getEasyApplySearchUrl()
self.goToUrl(searchUrl)
def goToUrl(self, url: str):
self.driver.get(url)
utils.sleepInBetweenActions()
def goToJobPage(self, jobID: str):
jobPage = 'https://www.linkedin.com/jobs/view/' + jobID
self.goToUrl(jobPage)
return jobPage
def processJob(self, jobID: str, jobCounter: models.JobCounter):
jobPage = self.goToJobPage(jobID)
jobCounter.total += 1
utils.sleepInBetweenBatches(jobCounter.total)
jobProperties = self.getJobPropertiesFromJobPage(jobID)
repository_wrapper.update_job(jobProperties)
if self.isJobBlacklisted(company=jobProperties.company, title=jobProperties.title):
jobCounter.skipped_blacklisted += 1
lineToWrite = self.getLogTextForJobProperties(jobProperties, jobCounter) + " | " + "* 🤬 Blacklisted Job, skipped!: " + str(jobPage)
self.displayWriteResults(lineToWrite)
else:
jobCounter = self.handleJobPost(
jobPage=jobPage,
jobProperties=jobProperties,
jobCounter=jobCounter)
return jobCounter
def getJobsFromSearchPage(self) -> List[models.JobForVerification]:
jobsListItems = self.driver.find_elements(By.XPATH,'//li[@data-occludable-job-id]')
jobsForVerification = []
for jobItem in jobsListItems:
companyName = None
jobTitle = None
workPlaceType = None
if self.exists(jobItem, By.XPATH, ".//*[contains(text(), 'Applied')]"):
if config.displayWarnings:
prYellow("⚠️ Not adding a job as I already applied to this job")
continue
# TODO Fix when some jobItems don't contain companyNameSpan which is not an expected behavior
companyNameSpan = jobItem.find_elements(By.XPATH, ".//span[contains(@class, 'job-card-container__primary-description')]")
if companyNameSpan:
full_description = companyNameSpan[0].text.strip()
textWithinParentheses = utils.extractTextWithinParentheses(full_description)
workPlaceType = self.verifyWorkPlaceType(textWithinParentheses)
if '·' in full_description:
companyName = full_description.split('·')[0].strip()
else:
companyName = full_description
if self.isCompanyBlacklisted(companyName):
if config.displayWarnings:
prYellow(f"⚠️ Not adding a job as the company '{companyName}' is blacklisted")
continue
if companyName is None:
utils.logDebugMessage("Couldn't find companyName", utils.MessageTypes.WARNING)
continue
jobTitleAnchor = jobItem.find_elements(By.XPATH, ".//a[contains(@class, 'job-card-container__link job-card-list__title')]")
if len(jobTitleAnchor) > 0:
allTexts = jobTitleAnchor[0].text.split("\n")
uniqueTexts = list(dict.fromkeys(allTexts))
jobTitle = uniqueTexts[0].strip()
if self.isTitleBlacklisted(jobTitle):
if config.displayWarnings:
prYellow(f"⚠️ Not adding a job as the title '{jobTitle}' is blacklisted")
continue
if jobTitle is None:
utils.logDebugMessage("Couldn't find jobTitle", utils.MessageTypes.WARNING)
continue
if jobTitle is None:
utils.logDebugMessage("Couldn't find jobTitle", utils.MessageTypes.WARNING)
continue
jobId = jobItem.get_attribute("data-occludable-job-id")
if jobId is None:
utils.logDebugMessage("Couldn't find jobID", utils.MessageTypes.WARNING)
continue
jobsForVerification.append(models.JobForVerification(
linkedinJobId=jobId.split(":")[-1],
title=jobTitle,
company=companyName,
workplaceType=workPlaceType))
return jobsForVerification
# TODO Move to logger.py (after splitting utils.py)
def getLogTextForJobProperties(self, jobProperties: models.Job, jobCounter: models.JobCounter):
textToWrite = str(jobCounter.total) + " | " + jobProperties.title + " | " + jobProperties.company + " | " + jobProperties.location + " | " + jobProperties.workplace_type + " | " + jobProperties.posted_date + " | " + jobProperties.applicants_at_time_of_applying
if self.isJobBlacklisted(company=jobProperties.company, title=jobProperties.title):
textToWrite = textToWrite + " | " + "blacklisted"
return textToWrite
def handleJobPost(self, jobPage, jobProperties: models.Job, jobCounter: models.JobCounter):
if self.isEasyApplyButtonDisplayed():
self.clickEasyApplyButton()
if self.isApplicationPopupDisplayed():
# Now, the easy apply popup should be open
if self.exists(self.driver, By.CSS_SELECTOR, constants.submitApplicationButtonCSS):
jobCounter = self.handleSubmitPage(jobPage, jobProperties, jobCounter)
elif self.exists(self.driver, By.CSS_SELECTOR, constants.nextPageButtonCSS):
jobCounter = self.handleMultiplePages(jobPage, jobProperties, jobCounter)
else:
jobCounter.skipped_already_applied += 1
lineToWrite = self.getLogTextForJobProperties(jobProperties, jobCounter) + " | " + "* 🥳 Already applied! Job: " + str(jobPage)
self.displayWriteResults(lineToWrite)
return jobCounter
def chooseResumeIfPossible(self, jobProperties: models.Job):
if self.isResumePage():
utils.interact(lambda : self.clickIfExists(By.CSS_SELECTOR, "button[aria-label='Show more resumes']"))
# Find all CV container elements
cv_containers = self.driver.find_elements(By.CSS_SELECTOR, ".jobs-document-upload-redesign-card__container")
# Loop through the elements to find the desired CV
for container in cv_containers:
cv_name_element = container.find_element(By.CLASS_NAME, "jobs-document-upload-redesign-card__file-name")
if config.distinctCVKeyword[0] in cv_name_element.text:
# Check if CV is already selected
if 'jobs-document-upload-redesign-card__container--selected' not in container.get_attribute('class'):
utils.interact(lambda : self.click_button(cv_name_element))
# Update the backend to save the selected CV
repository_wrapper.attached_resume_to_job(jobProperties, cv_name_element.text)
# exit the loop once the desired CV is found and selected
break
def isResumePage(self):
upload_button_present = self.exists(self.driver, By.CSS_SELECTOR, "label.jobs-document-upload__upload-button")
resume_container_present = self.exists(self.driver, By.CSS_SELECTOR, "div.jobs-document-upload-redesign-card__container")
return upload_button_present and resume_container_present
def getJobPropertiesFromJobPage(self, jobID: str) -> models.Job:
jobTitle = self.getJobTitleFromJobPage()
jobCompany = self.getJobCompanyFromJobPage()
jobLocation = ""
jobPostedDate = ""
numberOfApplicants = ""
jobWorkPlaceType = self.getJobWorkPlaceTypeFromJobPage()
jobDescription = self.getJobDescriptionFromJobPage()
# First, find the container that holds all the elements.
if self.exists(self.driver, By.XPATH, "//div[contains(@class, 'job-details-jobs-unified-top-card__primary-description-container')]//div"):
primary_description_div = self.driver.find_element(By.XPATH, "//div[contains(@class, 'job-details-jobs-unified-top-card__primary-description-container')]//div")
jobLocation = self.getJobLocationFromJobPage(primary_description_div)
jobPostedDate = self.getJobPostedDateFromJobPage(primary_description_div)
numberOfApplicants = self.getNumberOfApplicantsFromJobPage(primary_description_div)
else:
utils.logDebugMessage("in getting primary_description_div", utils.MessageTypes.WARNING)
return models.Job(
title=jobTitle,
company=jobCompany,
location=jobLocation,
description=jobDescription,
workplace_type=jobWorkPlaceType,
posted_date=jobPostedDate,
applicants_at_time_of_applying=numberOfApplicants,
linkedin_job_id=jobID
)
def getJobTitleFromJobPage(self) -> str:
jobTitle = ""
try:
jobTitleElement = self.driver.find_element(By.CSS_SELECTOR, "h1.t-24.t-bold.inline")
jobTitle = jobTitleElement.text.strip()
except Exception as e:
utils.logDebugMessage("in getting jobTitle", utils.MessageTypes.WARNING, e)
return jobTitle
def getJobCompanyFromJobPage(self) -> str:
jobCompany = ""
if self.exists(self.driver, By.XPATH, "//div[contains(@class, 'job-details-jobs-unified-top-card__company-name')]//a"):
# Inside this container, find the company name link.
jobCompanyElement = self.driver.find_element(By.XPATH, "//div[contains(@class, 'job-details-jobs-unified-top-card__company-name')]//a")
jobCompany = jobCompanyElement.text.strip()
else:
utils.logDebugMessage("in getting jobCompany card", utils.MessageTypes.WARNING)
return jobCompany
def getJobLocationFromJobPage(self, primary_description_div) -> str:
jobLocation = ""
try:
jobLocationSpan = primary_description_div.find_element(By.XPATH, ".//span[contains(@class, 'tvm__text--low-emphasis')][1]")
jobLocation = jobLocationSpan.text.strip()
except Exception as e:
utils.logDebugMessage("in getting jobLocation", utils.MessageTypes.WARNING, e)
return jobLocation
def getJobPostedDateFromJobPage(self, primary_description_div) -> str:
jobPostedDate = ""
try:
primary_description_text = primary_description_div.text # Get all text from the div
# Regex pattern to find patterns like '6 hours ago', '2 days ago', etc.
match = re.search(r'\b\d+\s+(seconds?|minutes?|hours?|days?|weeks?|months?)\s+ago\b', primary_description_text)
if match:
jobPostedDate = match.group(0) # The whole matched text is the date
except Exception as e:
utils.logDebugMessage("Error in getting jobPostedDate", utils.MessageTypes.WARNING, e)
return jobPostedDate
def getNumberOfApplicantsFromJobPage(self, primary_description_div) -> str:
jobApplications = ""
try:
# Find all spans with the class 'tvm__text--low-emphasis'
primaryDescriptionSpans = primary_description_div.find_elements(By.XPATH, ".//span[contains(@class, 'tvm__text--low-emphasis')]")
# Loop through all found spans in reverse order because the number of applicants is usually the last one
for span in reversed(primaryDescriptionSpans):
span_text = span.text.strip()
# Check if the text contains the keyword 'appl' (from 'applicants' or 'applications') and a number
if 'appl' in span_text.lower() and any(char.isdigit() for char in span_text):
jobApplications = span_text
break
except Exception as e:
utils.logDebugMessage("in getting jobApplications", utils.MessageTypes.WARNING, e)
return jobApplications
def getJobWorkPlaceTypeFromJobPage(self) -> str:
jobWorkPlaceType = ""
try:
jobWorkPlaceTypeElement = self.driver.find_element(By.XPATH, "//li[contains(@class, 'job-details-jobs-unified-top-card__job-insight')]/span/span")
firstSpanText = jobWorkPlaceTypeElement.text.strip().split('\n')[0]
jobWorkPlaceType = self.verifyWorkPlaceType(firstSpanText)
except Exception as e:
utils.logDebugMessage("in getting jobWorkPlaceType", utils.MessageTypes.WARNING, e)
return jobWorkPlaceType
# TODO Find a faster way to verify workplace type
def verifyWorkPlaceType(self, text: str) -> str:
keywords = ["Remote", "On-site", "Hybrid"]
if any(text in keyword for keyword in keywords):
return text
else:
return ""
# TODO Use jobDetail later
def getJobDescriptionFromJobPage(self):
jobDescription = ""
try:
# Directly target the div with the specific ID that contains the job description
descriptionContainer = self.driver.find_element(By.ID, "job-details")
jobDescription = descriptionContainer.text # This should get all text within, including nested spans and divs
except Exception as e:
utils.logDebugMessage("in getting jobDescription: ", utils.MessageTypes.WARNING, e)
return jobDescription
def isJobBlacklisted(self, company: str, title: str):
is_blacklisted = self.isCompanyBlacklisted(company)
if is_blacklisted:
return True
is_blacklisted = self.isTitleBlacklisted(title)
if is_blacklisted:
return True
return False
def isCompanyBlacklisted(self, company: str):
return any(blacklistedCompany.strip().lower() == company.lower() for blacklistedCompany in config.blacklistCompanies)
def isTitleBlacklisted(self, title: str):
return any(blacklistedTitle.strip().lower() in title.lower() for blacklistedTitle in config.blackListTitles)
def handleMultiplePages(self, jobPage, jobProperties: models.Job, jobCounter: models.JobCounter):
self.clickNextButton()
# TODO Change the logic when answering to questions is implemented
if self.isErrorMessageDisplayed():
jobCounter = self.cannotApply(jobPage, jobProperties, jobCounter)
return jobCounter
percentageElement = self.driver.find_element(By.XPATH, constants.multiplePagePercentageXPATH)
comPercentage = percentageElement.get_attribute("value")
percentage = int(comPercentage)
applyPages = math.ceil(100 / percentage) - 2
try:
for _ in range(applyPages):
self.handleApplicationStep(jobProperties)
if self.isApplicationStepDisplayed():
self.clickNextButton()
self.handleApplicationStep(jobProperties)
if self.isLastApplicationStepDisplayed():
self.clickReviewApplicationButton()
jobCounter = self.handleSubmitPage(jobPage, jobProperties, jobCounter)
except:
jobCounter = self.cannotApply(jobPage, jobProperties, jobCounter)
return jobCounter
def cannotApply(self, jobPage, jobProperties: models.Job, jobCounter: models.JobCounter) -> models.JobCounter:
jobCounter.skipped_unanswered_questions += 1
# TODO Instead of except, output which questions need to be answered
lineToWrite = self.getLogTextForJobProperties(jobProperties, jobCounter) + " | " + "* 🥵 Couldn't apply to this job! Extra info needed. Link: " + str(jobPage)
self.displayWriteResults(lineToWrite)
return jobCounter
def handleSubmitPage(self, jobPage, jobProperties: models.Job, jobCounter: models.JobCounter):
followCompany = self.driver.find_element(By.CSS_SELECTOR,"label[for='follow-company-checkbox']")
# Use JavaScript to check the state of the checkbox
is_followCompany_checked = self.driver.execute_script("""
var label = arguments[0];
var checkbox = document.getElementById('follow-company-checkbox');
var style = window.getComputedStyle(label, '::after');
var content = style.getPropertyValue('content');
// Check if content is not 'none' or empty which may indicate the presence of the ::after pseudo-element
return checkbox.checked || (content && content !== 'none' && content !== '');
""", followCompany)
if config.followCompanies != is_followCompany_checked:
utils.interact(lambda : self.click_button(followCompany))
if self.isReviewApplicationStepDisplayed():
self.clickSubmitApplicationButton()
if self.isApplicationSubmittedDialogDisplayed():
repository_wrapper.applied_to_job(jobProperties)
lineToWrite = self.getLogTextForJobProperties(jobProperties, jobCounter) + " | " + "* 🥳 Just Applied to this job: " + str(jobPage)
self.displayWriteResults(lineToWrite)
jobCounter.applied += 1
return jobCounter
# TODO Move to logger.py (after splitting utils.py)
def displayWriteResults(self, lineToWrite: str):
try:
prYellow(lineToWrite)
utils.writeResults(lineToWrite)
except Exception as e:
prRed("❌ Error in DisplayWriteResults: " + str(e))
def handleApplicationStep(self, jobProperties: models.Job):
self.chooseResumeIfPossible(jobProperties)
# self.handleQuestions(jobProperties)
def handleQuestions(self, jobProperties: models.Job):
if self.exists(self.driver, By.CSS_SELECTOR, "div.pb4"):
# Locate the div that contains all the questions
questionsContainer = self.driver.find_element(By.CSS_SELECTOR, "div.pb4")
if self.exists(questionsContainer, By.CSS_SELECTOR, "div.jobs-easy-apply-form-section__grouping"):
# Find all question groups within that div
questionGroups = questionsContainer.find_elements(By.CSS_SELECTOR, "div.jobs-easy-apply-form-section__grouping")
# Iterate through each question group
for group in questionGroups:
# TODO Next commented code is to handle city selection and other dropdowns
"""
# Find the element (assuming you have a way to locate this div, here I'm using a common class name they might share)
div_element = self.driver.find_element(By.CLASS_NAME, "common-class-name")
# Check for the specific data-test attribute
if div_element.get_attribute("data-test-single-typeahead-entity-form-component") is not None:
# Handle the first type of div
print("This is the first type of div with data-test-single-typeahead-entity-form-component")
elif div_element.get_attribute("data-test-single-line-text-form-component") is not None:
# Handle the second type of div
print("This is the second type of div with data-test-single-line-text-form-component")
else:
# Handle the case where the div doesn't match either type
print("The div doesn't match either specified type")
"""
if self.exists(group, By.CSS_SELECTOR, "label.artdeco-text-input--label"):
# Find the label for the question within the group
questionLabel = group.find_element(By.CSS_SELECTOR, "label.artdeco-text-input--label").text
# Determine the type of question and call the appropriate handler
if self.exists(group, By.CSS_SELECTOR, "input.artdeco-text-input--input"):
self.handleTextInput(group, questionLabel, By.CSS_SELECTOR, "input.artdeco-text-input--input")
elif self.exists(group, By.CSS_SELECTOR, "textarea"):
self.handleTextInput(group, questionLabel, By.CSS_SELECTOR, "textarea")
elif self.exists(group, By.CSS_SELECTOR, "input[type='radio']"):
self.handleRadioInput(group, questionLabel, By.CSS_SELECTOR, "input[type='radio']")
else:
self.logUnhandledQuestion(questionLabel)
def exists(self, parent, by, value):
# Check if an element exists on the page
return len(parent.find_elements(by, value)) > 0
def isEasyApplyButtonDisplayed(self):
return self.exists(self.driver, By.CSS_SELECTOR, constants.easyApplyButtonCSS)
def clickEasyApplyButton(self):
button = self.driver.find_element(By.CSS_SELECTOR, constants.easyApplyButtonCSS)
utils.interact(lambda : self.click_button(button))
def isApplicationPopupDisplayed(self):
return self.exists(self.driver, By.XPATH, constants.jobApplicationHeaderXPATH)
def isApplicationStepDisplayed(self):
return self.exists(self.driver, By.CSS_SELECTOR, constants.nextPageButtonCSS)
def clickNextButton(self):
button = self.driver.find_element(By.CSS_SELECTOR, constants.nextPageButtonCSS)
utils.interact(lambda : self.click_button(button))
def isLastApplicationStepDisplayed(self):
return self.exists(self.driver, By.CSS_SELECTOR, constants.reviewApplicationButtonCSS)
def clickReviewApplicationButton(self):
button = self.driver.find_element(By.CSS_SELECTOR, constants.reviewApplicationButtonCSS)
utils.interact(lambda : self.click_button(button))
def isReviewApplicationStepDisplayed(self):
return self.exists(self.driver, By.CSS_SELECTOR, constants.submitApplicationButtonCSS)
def clickSubmitApplicationButton(self):
button = self.driver.find_element(By.CSS_SELECTOR, constants.submitApplicationButtonCSS)
utils.interact(lambda : self.click_button(button))
def isApplicationSubmittedDialogDisplayed(self):
dialog = self.driver.find_element(By.CSS_SELECTOR, "div[data-test-modal][role='dialog']")
dismiss_button_present = self.exists(dialog, By.CSS_SELECTOR, "button[aria-label='Dismiss']")
return dismiss_button_present
def isErrorMessageDisplayed(self):
return self.exists(self.driver, By.CSS_SELECTOR, constants.errorMessageForNecessaryFiledCSS)
def handleTextInput(self, group, questionLabel, by, value):
# Locate the input element
inputElement = group.find_element(by, value)
# Retrieve the value of the input element
inputValue = inputElement.get_attribute('value')
# Check if the input element is empty
if inputValue == '':
# TODO Check the backend for answers
# TODO If there is an answer for this question, fill it in
# If you want to fill the input
# question_input.send_keys("Your answer here") then sleep
# If no answers are found, move to the next step (backend should handle saving unanswered questions)
if config.displayWarnings:
prYellow(f"The input for '{questionLabel}' is empty.")
else:
# TODO Save answers to the backend if they are not already saved
if config.displayWarnings:
prYellow(f"The input for '{questionLabel}' has the following value: {inputValue}")
def handleRadioInput(self, group, questionLabel, by, value):
# Check if it's a radio selector question
radioInputs = group.find_elements(by, value)
for radioInput in radioInputs:
# Retrieve the associated label
label = radioInput.find_element(By.XPATH, "./following-sibling::label").text
# TODO Check the backend for answers. If there is an answer for this question, fill it in
# Check or uncheck based on some condition
# if "desired option" in label:
# prYellow(f"Selecting option: {label}")
# radio_input.click() # Select the radio button if it's the desired option then sleep
def logUnhandledQuestion(self, questionLabel):
# Log or print the unhandled question
prRed(f"Unhandled question: {questionLabel}")
def clickIfExists(self, by, selector):
if self.exists(self.driver, by, selector):
clickableElement = self.driver.find_element(by, selector)
self.click_button(clickableElement)
def click_button(self, button):
try:
button.click()
except Exception as e:
# If click fails, use JavaScript to click on the button
self.driver.execute_script("arguments[0].click();", button)