forked from wodsuz/EasyApplyJobsBot
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
executable file
·409 lines (335 loc) · 13.1 KB
/
utils.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
import math
import os
import random
import time
import traceback
import re
from enum import Enum
from typing import List
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import config
import constants
def chromeBrowserOptions():
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument("--ignore-certificate-errors")
options.add_argument("--disable-extensions")
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')
if(config.headless):
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--disable-blink-features")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])
if(len(config.chromeProfilePath)>0):
initialPath = config.chromeProfilePath[0:config.chromeProfilePath.rfind("/")]
profileDir = config.chromeProfilePath[config.chromeProfilePath.rfind("/")+1:]
options.add_argument('--user-data-dir=' + initialPath)
options.add_argument("--profile-directory=" + profileDir)
else:
# options.add_argument("--incognito")
# this is for running in a docker container
user_data_dir = os.environ.get('CHROME_USER_DATA_DIR', '/home/user/chrome_data')
options.add_argument(f'--user-data-dir={user_data_dir}')
return options
def prRed(prt):
print(f"\033[91m{prt}\033[00m")
def prGreen(prt):
print(f"\033[92m{prt}\033[00m")
def prYellow(prt):
print(f"\033[93m{prt}\033[00m")
def prBlue(prt):
print(f"\033[94m{prt}\033[00m")
class MessageTypes(Enum):
INFO = 1
WARNING = 2
ERROR = 3
SUCCESS = 4
def printInfoMes(bot:str):
prYellow("ℹ️ " +bot+ " is starting soon... ")
def logDebugMessage(message, messageType=MessageTypes.INFO, exception=Exception(), displayTraceback = False):
if (config.displayWarnings):
match messageType:
case MessageTypes.INFO:
prBlue(f"ℹ️ {message}")
case MessageTypes.WARNING:
prYellow(f"⚠️ Warning ⚠️ {message}: {str(exception)[0:100]}")
case MessageTypes.ERROR:
prRed(f"❌ Error ❌ {message}: {str(exception)[0:100]}")
case MessageTypes.SUCCESS:
prGreen(f"✅ {message}")
if (displayTraceback):
traceback.print_exc()
def jobsToPages(numOfJobs: str) -> int:
number_of_pages = 1
if (' ' in numOfJobs):
spaceIndex = numOfJobs.index(' ')
totalJobs = (numOfJobs[0:spaceIndex])
totalJobs_int = int(totalJobs.replace(',', ''))
number_of_pages = math.ceil(totalJobs_int/constants.jobsPerPage)
if (number_of_pages > 40 ): number_of_pages = 40
else:
number_of_pages = int(numOfJobs)
return number_of_pages
def urlToKeywords(url: str) -> List[str]:
keywordUrl = url[url.index("keywords=")+9:]
keyword = keywordUrl[0:keywordUrl.index("&") ]
locationUrl = url[url.index("location=")+9:]
location = locationUrl[0:locationUrl.index("&") ]
return [keyword,location]
def writeResults(text: str):
timeStr = time.strftime("%Y%m%d")
directory = "data"
fileName = "Applied Jobs DATA - " + timeStr + ".txt"
filePath = os.path.join(directory, fileName)
try:
os.makedirs(directory, exist_ok=True) # Ensure the 'data' directory exists.
# Open the file for reading and writing ('r+' opens the file for both)
with open(filePath, 'r+', encoding="utf-8") as file:
lines = []
for line in file:
if "----" not in line:
lines.append(line)
file.seek(0) # Go back to the start of the file
file.truncate() # Clear the file
file.write("---- Applied Jobs Data ---- created at: " + timeStr + "\n")
file.write("---- Number | Job Title | Company | Location | Work Place | Posted Date | Applications | Result " + "\n")
for line in lines:
file.write(line)
file.write(text + "\n")
except FileNotFoundError:
with open(filePath, 'w', encoding="utf-8") as f:
f.write("---- Applied Jobs Data ---- created at: " + timeStr + "\n")
f.write("---- Number | Job Title | Company | Location | Work Place | Posted Date | Applications | Result " + "\n")
f.write(text + "\n")
except Exception as e:
prRed(f"❌ Error in writeResults: {e}") # Assuming prRed is a function to print errors in red color
# def writeResults(text: str):
# timeStr = time.strftime("%Y%m%d")
# fileName = "Applied Jobs DATA - " +timeStr + ".txt"
# try:
# with open("data/" +fileName, encoding="utf-8" ) as file:
# lines = []
# for line in file:
# if "----" not in line:
# lines.append(line)
# with open("data/" +fileName, 'w' ,encoding="utf-8") as f:
# f.write("---- Applied Jobs Data ---- created at: " +timeStr+ "\n" )
# f.write("---- Number | Job Title | Company | Location | Work Place | Posted Date | Applications | Result " +"\n" )
# for line in lines:
# f.write(line)
# f.write(text+ "\n")
# except:
# with open("data/" +fileName, 'w', encoding="utf-8") as f:
# f.write("---- Applied Jobs Data ---- created at: " +timeStr+ "\n" )
# f.write("---- Number | Job Title | Company | Location | Work Place | Posted Date | Applications | Result " +"\n" )
# f.write(text+ "\n")
def interact(action):
action()
sleepInBetweenActions()
def sleepInBetweenActions(bottom: int = constants.botSleepInBetweenActionsBottom, top: int = constants.botSleepInBetweenActionsTop):
time.sleep(random.uniform(bottom, top))
def sleepInBetweenBatches(currentBatch: int, bottom: int = constants.botSleepInBetweenBatchesBottom, top: int = constants.botSleepInBetweenBatchesTop):
if (currentBatch % constants.batchSize == 0):
time.sleep(random.uniform(bottom, top))
def extractTextWithinParentheses(text):
# Pattern to match text within parentheses
pattern = r"\((.*?)\)"
match = re.search(pattern, text)
if match:
# Return the content within the first set of parentheses
return match.group(1) # `group(1)` returns the content within the parentheses
else:
return ""
class LinkedinUrlGenerator:
@staticmethod
def getGeneralSearchUrl():
return constants.searchJobsUrl
@staticmethod
def getEasyApplySearchUrl():
return constants.searchEasyApplyJobsUrl
def generateSearchUrls(self):
urls = []
for location in config.location:
for keyword in config.keywords:
url = constants.searchJobsUrl + "?f_AL=true&keywords=" + keyword + self.jobType() + self.remote() + self.checkJobLocation(location) + self.jobExp() + self.datePosted() + self.jobTitle() + self.salary() + self.sortBy()
urls.append(url)
return urls
def checkJobLocation(self, job):
jobLoc = "&location=" + job
match job.casefold():
case "asia":
jobLoc += "&geoId=102393603"
case "europe":
jobLoc += "&geoId=100506914"
case "northamerica":
jobLoc += "&geoId=102221843&"
case "southamerica":
jobLoc += "&geoId=104514572"
case "australia":
jobLoc += "&geoId=101452733"
case "africa":
jobLoc += "&geoId=103537801"
case "sweden":
jobLoc += "&geoId=105117694"
case "norway":
jobLoc += "&geoId=103819153"
case "germany":
jobLoc += "&geoId=101282230"
case "switzerland":
jobLoc += "&geoId=106693272"
case "new york":
jobLoc += "&geoId=105080838"
return jobLoc
def jobExp(self):
jobtExpArray = config.experienceLevels
firstJobExp = jobtExpArray[0]
jobExp = ""
match firstJobExp:
case "Internship":
jobExp = "&f_E=1"
case "Entry level":
jobExp = "&f_E=2"
case "Associate":
jobExp = "&f_E=3"
case "Mid-Senior level":
jobExp = "&f_E=4"
case "Director":
jobExp = "&f_E=5"
case "Executive":
jobExp = "&f_E=6"
for index in range (1,len(jobtExpArray)):
match jobtExpArray[index]:
case "Internship":
jobExp += "%2C1"
case "Entry level":
jobExp +="%2C2"
case "Associate":
jobExp +="%2C3"
case "Mid-Senior level":
jobExp += "%2C4"
case "Director":
jobExp += "%2C5"
case "Executive":
jobExp +="%2C6"
return jobExp
def datePosted(self):
datePosted = ""
match config.datePosted[0]:
case "Any Time":
datePosted = ""
case "Past Month":
datePosted = "&f_TPR=r2592000&"
case "Past Week":
datePosted = "&f_TPR=r604800&"
case "Past 24 hours":
datePosted = "&f_TPR=r86400&"
return datePosted
def jobType(self):
jobTypeArray = config.jobType
firstjobType = jobTypeArray[0]
jobType = ""
match firstjobType:
case "Full-time":
jobType = "&f_JT=F"
case "Part-time":
jobType = "&f_JT=P"
case "Contract":
jobType = "&f_JT=C"
case "Temporary":
jobType = "&f_JT=T"
case "Volunteer":
jobType = "&f_JT=V"
case "Intership":
jobType = "&f_JT=I"
case "Other":
jobType = "&f_JT=O"
for index in range (1,len(jobTypeArray)):
match jobTypeArray[index]:
case "Full-time":
jobType += "%2CF"
case "Part-time":
jobType +="%2CP"
case "Contract":
jobType +="%2CC"
case "Temporary":
jobType += "%2CT"
case "Volunteer":
jobType += "%2CV"
case "Intership":
jobType +="%2CI"
case "Other":
jobType +="%2CO"
jobType += "&"
return jobType
def remote(self):
remoteArray = config.remote
firstJobRemote = remoteArray[0]
jobRemote = ""
match firstJobRemote:
case "On-site":
jobRemote = "f_WT=1"
case "Remote":
jobRemote = "f_WT=2"
case "Hybrid":
jobRemote = "f_WT=3"
for index in range (1,len(remoteArray)):
match remoteArray[index]:
case "On-site":
jobRemote += "%2C1"
case "Remote":
jobRemote += "%2C2"
case "Hybrid":
jobRemote += "%2C3"
return jobRemote
def jobTitle(self):
jobTitleArray = config.jobTitles
# Ensure we have at least one job title to process
if not jobTitleArray:
return ""
# Use the first job title for the initial job title parameter
initial_code = constants.job_title_codes.get(jobTitleArray[0])
if initial_code:
jobTitle = f"f_T={initial_code}"
else:
return "" # If the first job title isn't recognized, return an empty string or handle error appropriately
# Process subsequent job titles
for title in jobTitleArray[1:]:
code = constants.job_title_codes.get(title)
if code:
jobTitle += f"%2C{code}"
jobTitle += "&"
return jobTitle
def salary(self):
salary = ""
match config.salary:
case "$40,000+":
salary = "f_SB2=1&"
case "$60,000+":
salary = "f_SB2=2&"
case "$80,000+":
salary = "f_SB2=3&"
case "$100,000+":
salary = "f_SB2=4&"
case "$120,000+":
salary = "f_SB2=5&"
case "$140,000+":
salary = "f_SB2=6&"
case "$160,000+":
salary = "f_SB2=7&"
case "$180,000+":
salary = "f_SB2=8&"
case "$200,000+":
salary = "f_SB2=9&"
return salary
def sortBy(self):
sortBy = ""
match config.sort[0]:
case "Recent":
sortBy = "sortBy=DD"
case "Relevent":
sortBy = "sortBy=R"
return sortBy