Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
550 lines (433 loc) · 23 KB
/
Copy pathmain.py
File metadata and controls
550 lines (433 loc) · 23 KB
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
# Global imports
from bs4 import BeautifulSoup as bs
from datetime import datetime, timedelta
from os.path import isfile
from pathlib import Path
from selenium.webdriver.common.by import By
from typing import Dict, List, Set
import os
import pandas as pd
import re
# Local imports
from browser import Browser
from config import *
BASE_DIR = Path(__file__).resolve().parent
def main():
def check_if_authwall(browser:Browser) -> bool:
page_title = browser.get_element(By.CLASS_NAME, 'authwall-join-form__title')
if page_title is not None:
return True
return False
def check_if_jobs_page_empty(browser: Browser) -> bool:
empty_text = browser.get_element(By.XPATH, f'//h1[contains(text(), "find a match for")]')
if empty_text is not None:
return True
return False
def enhance_company_list(filepath: str = None, filedir: str = None, check_against_masterlist: bool = True, add_to_masterlist: bool = False) -> None:
if filepath is None and filedir is None:
print('Please provide either file or directory for processing')
return
company_files = []
if filepath is not None:
company_files.append(filepath)
else:
dir_path = filedir
company_files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if isfile(os.path.join(dir_path, f))]
if os.path.isfile(f'{BASE_DIR}{COMPANIES_MASTERLIST}'):
masterfile_df = pd.read_csv(f'{BASE_DIR}{COMPANIES_MASTERLIST}')
for file in company_files:
try:
print(f'Processing file {file}')
companies_df_in = pd.read_csv(file)
if 'SECTOR' in companies_df_in.columns:
companies_df_in = companies_df_in[~companies_df_in['SECTOR'].isin(SKIP_INDUSTRIES)]
companies_list_out = []
skipped_counter = 0
for index, row in companies_df_in.iterrows():
if 'COMPANY_NAME' in row:
print(f'Processing company record - {row['COMPANY_NAME']}')
if check_against_masterlist and is_in_masterlist(company_row=row):
print(f'Company already in masterlist. Will skip.')
skipped_counter +=1
continue
if 'URL' not in row:
company_url = get_company_named_link(row['COMPANY_ID'])
else:
company_url = row['URL']
company_details = {}
if company_url is not None:
company_details = get_company_details(url=company_url)
company_id = None
if 'COMPANY_ID' in row:
company_id = row['COMPANY_ID']
elif 'COMPANY_ID' in company_details:
company_id = company_details['COMPANY_ID']
company_name = None
if 'COMPANY_NAME' in row:
company_name = row['COMPANY_NAME']
elif 'COMPANY_NAME' in company_details:
company_name = company_details['COMPANY_NAME']
company_sector = None
if 'INDUSTRY' in row:
company_sector = row['INDUSTRY']
elif 'INDUSTRY' in company_details:
company_sector = company_details['INDUSTRY']
company_hq = None
if 'LOCATION' in row:
company_hq = row['LOCATION']
elif 'LOCATION' in company_details:
company_hq = company_details['LOCATION']
company_description = None
if 'DESCRIPTION' in row:
company_description = row['DESCRIPTION']
elif 'DESCRIPTION' in company_details:
company_description = company_details['DESCRIPTION']
company_dict = {
'COMPANY_ID': company_id,
'COMPANY_NAME': company_name,
'URL': company_url,
'INDUSTRY': company_sector,
'LOCATION': company_hq,
'DESCRIPTION': company_description,
}
companies_list_out.append(company_dict)
except Exception as e:
print('Something went wrong')
print(e)
finally:
if len(companies_list_out)>0 :
new_file_name = Path(file).stem
companies_df_out = pd.DataFrame(companies_list_out)
companies_df_out['COMPANY_ID'] = companies_df_out['COMPANY_ID'].astype('Int64')
companies_df_out.to_csv(
f'{BASE_DIR}{ENHANCED_COMPANY_LIST_DIR}{new_file_name}.csv',
index=False,
)
print(f'File {file} processed. {skipped_counter} record skipped.')
if add_to_masterlist:
refresh_masterlist()
def gather_companies(check_against_masterlist: bool = True) -> None:
try:
companies_list = []
checked_urls = []
new_urls = [START_COMPANY_URL]
while len(new_urls) > 0 and len(companies_list) < MAX_SIMILAR_COMPANIES:
browser = Browser()
url = new_urls.pop()
print(f'Checking URL: {url}')
browser.open_page(url)
reject_login(browser)
reject_cookies(browser)
reject_popup(browser)
right_pane = bs(
browser.get_element(By.CLASS_NAME, 'right-rail').get_attribute('outerHTML'),
'html.parser',
)
side_cards = right_pane.find_all('section', {'class': 'aside-section-container'})
for side_card in side_cards:
title = side_card.find('h2', {'class': 'aside-section-container__title'}).text.strip()
if title in ['Similar pages', 'Affiliated pages']:
similar_companies_list = side_card.find('ul', {'class': 'show-more-less__list'})
similar_companies = similar_companies_list.find_all('li', recursive=False)
for company in similar_companies:
company_url = company.find('a', {'class': 'base-card'})['href'].split('?')[0]
company_name = company.find('h3', {'class': 'base-aside-card__title'}).text.strip()
company_sector = company.find('p', {'class': 'base-aside-card__subtitle'})
if company_sector is not None:
company_sector = company_sector.text.strip()
company_hq = company.find('p', {'class': 'base-aside-card__second-subtitle'})
if company_hq is not None:
company_hq = company_hq.text.strip()
if company_url not in checked_urls and company_url not in new_urls:
if company_sector not in SKIP_INDUSTRIES and company_hq not in SKIP_LOCATIONS:
if not check_against_masterlist or not is_in_masterlist(company_url=company_url):
companies_list.append(
{
'COMPANY_NAME': company_name,
'SECTOR': company_sector,
'URL': company_url,
'HQ_LOCATION': company_hq,
}
)
new_urls.append(company_url)
browser.quit()
checked_urls.append(url)
except Exception as e:
print("This exception happened:")
print(e)
finally:
companies_df = pd.DataFrame(companies_list)
companies_df['COMPANY_ID'] = companies_df['COMPANY_ID'].astype('Int64')
companies_df.to_csv(
f'{BASE_DIR}{SIMILAR_COMPANIES_LIST_DIR}{START_COMPANY_URL.split("/")[-1]}.csv',
index=False,
)
def gather_jobs(filepath: str = None, target_industries: bool = False) -> None:
browser = Browser()
if filepath is None:
filepath = f'{BASE_DIR}{COMPANIES_MASTERLIST}'
try:
print(f'Will check for jobs in these companies: {filepath}')
companies_df = pd.read_csv(filepath)
except FileNotFoundError:
print("The input file does not exist!")
else:
try:
companies_df = companies_df.dropna(subset=['COMPANY_ID'])
companies_df = companies_df[~companies_df['COMPANY_ID'].isin(SKIP_COMPANIES_IDS)]
companies_df = companies_df[~companies_df['COMPANY_NAME'].isin(SKIP_COMPANIES_NAMES)]
if target_industries and len(TARGET_INDUSTRIES) > 0:
companies_df['INDUSTRY'] = companies_df['INDUSTRY'].str.strip()
companies_df['INDUSTRY'] = companies_df['INDUSTRY'].str.lower()
target_industries = [industry.lower() for industry in TARGET_INDUSTRIES]
companies_df = companies_df[companies_df['INDUSTRY'].isin(target_industries)]
companies_last_check_df = pd.read_csv(f'{BASE_DIR}{JOBS_LAST_CHECK_DATES}')
last_check_cutoff = datetime.today() - timedelta(days = COOLDOWN_DAYS)
companies_last_check_df['LAST_CHECK_DATE'] = pd.to_datetime(companies_last_check_df['LAST_CHECK_DATE'])
skip_companies_df = companies_last_check_df[companies_last_check_df['LAST_CHECK_DATE']> last_check_cutoff]
skip_companies_list = skip_companies_df['COMPANY_ID'].to_list()
companies_df = companies_df[~companies_df['COMPANY_ID'].isin(skip_companies_list)]
skip_jobs_df = pd.read_csv(f'{BASE_DIR}{SKIP_JOBS_LIST}')
skip_jobs_urls = skip_jobs_df['JOB_URL'].to_list()
job_list = []
checked_company_list = []
for index, row in companies_df.iterrows():
print(f'Checking jobs at {row['COMPANY_NAME']}')
company_id = int(row['COMPANY_ID'])
is_authwall = True
while is_authwall:
open_jobs_page(browser, company_id) # open page for all UK jobs to see if any exist
is_authwall = check_if_authwall(browser)
if not check_if_jobs_page_empty(browser): # if some UK jobs exist, check for keywords
for keyword in JOB_KEYWORDS:
is_authwall = True
while is_authwall:
open_jobs_page(browser, company_id, keyword = keyword)
is_authwall = check_if_authwall(browser)
if not check_if_jobs_page_empty(browser):
job_li_list = get_job_cards(browser)
print(f'{keyword} got {len(job_li_list)} potential jobs')
for job in job_li_list:
job_url = job.find('a', {'class': 'base-card__full-link'})['href'].split('?')[0]
job_title = job.find('h3', {'class': 'base-search-card__title'}).text.strip()
job_location = job.find('span', {'class': 'job-search-card__location'}).text.strip()
if not any(keyword.lower() in job_title.lower() for keyword in SKIP_KEYWORDS):
if job_url not in skip_jobs_urls:
print(f'Logging job: {job_title}')
job_list.append(
{
'JOB_TITLE': job_title,
'COMPANY_NAME': row['COMPANY_NAME'],
'LOCATION': job_location,
'JOB_URL': job_url,
'COMPANY_URL': row['URL'],
'COMPANY_ID': company_id,
}
)
else:
print(f'Skipping job: {job_title} | {job_url}')
else:
print(f'{keyword} got an empty page')
browser.sleep(2)
else:
print(f'There are no UK jobs at {row['COMPANY_NAME']}')
checked_company_list.append(company_id)
except Exception as e:
print(f'An exception happened: {e}')
input()
finally:
if len(job_list) > 0:
job_list_df = pd.DataFrame(job_list)
job_list_df.drop_duplicates(subset=None, keep="first", inplace=True)
original_file_name = Path(filepath).stem
job_list_df.to_csv(
f'{BASE_DIR}{JOB_LIST_DIR}{original_file_name}_processed.csv',
index=False,
)
skip_jobs_df = pd.concat([skip_jobs_df, job_list_df], ignore_index=True, sort=False)
skip_jobs_df.to_csv(f'{BASE_DIR}{SKIP_JOBS_LIST}', index= False)
if len(checked_company_list) > 0:
checked_company_df = pd.DataFrame(checked_company_list, columns = ['COMPANY_ID'])
checked_company_df['LAST_CHECK_DATE'] =datetime.today()
companies_last_check_df = pd.concat(
[companies_last_check_df, checked_company_df], ignore_index=True, sort=False
)
companies_last_check_df['COMPANY_ID'] = companies_last_check_df['COMPANY_ID'].astype('Int64')
companies_last_check_df.to_csv(f'{BASE_DIR}{JOBS_LAST_CHECK_DATES}', index = False
)
def get_company_details(name: str = None, url: str = None) -> Dict[str, str]:
browser = Browser()
company_url = url
if name is not None:
company_url = f'https://uk.linkedin.com/company/{name}'
browser.open_page(company_url)
browser.sleep(2)
reject_login(browser)
reject_cookies(browser)
reject_popup(browser)
company_id = browser.get_element(By.XPATH, f'//a[contains(@href, "org-employees_cta_face-pile-cta")]')
if company_id is not None:
company_id = company_id.get_attribute('href').split('%255D')[0].split('%3D%255B')[-1].split('%252C%2B')[-1]
company_name = browser.get_element(By.CLASS_NAME, 'top-card-layout__title')
if company_name is not None:
company_name = company_name.text.strip()
company_industry = browser.get_element(By.CLASS_NAME, 'top-card-layout__headline')
if company_industry is not None:
company_industry = company_industry.text.strip()
company_hq = browser.get_element(By.CLASS_NAME, 'top-card-layout__first-subline')
if company_hq is not None:
company_hq = company_hq.get_attribute('innerHTML').split('<')[0].strip()
company_description = browser.get_element(By.CLASS_NAME, 'top-card-layout__second-subline')
if company_description is not None:
company_description = company_description.text.strip()
browser.quit()
company_dict = {
'COMPANY_ID': company_id,
'COMPANY_NAME': company_name,
'INDUSTRY': company_industry,
'LOCATION': company_hq,
'DESCRIPTION': company_description,
}
return company_dict
def get_company_named_link(company_id: int, browser: Browser = None) -> str:
if browser is None:
browser = Browser()
open_jobs_page(browser, company_id, 'worldwide')
named_link = None
try:
if not check_if_jobs_page_empty(browser):
job_list = get_job_cards(browser)
named_link = job_list[0].find('a', {'class': 'hidden-nested-link'})['href'].split('?')[0]
except Exception as e:
print(e)
print('Something went wrong. Is the job list open?')
finally:
browser.quit()
return named_link
def get_industries(filepath:str = None) -> Set[str]:
if filepath is None:
filepath = f'{BASE_DIR}{COMPANIES_MASTERLIST}'
try:
companies_df = pd.read_csv(filepath)
return set(companies_df['INDUSTRY'])
except:
print('Could not read the input file')
return set()
def get_job_cards(browser: Browser) -> List[bs]:
html = browser.get_element(By.TAG_NAME, 'html').get_attribute('innerHTML')
soup = bs(html, 'html.parser')
jobs_ul = soup.find('ul', {'class': 'jobs-search__results-list'})
job_li_list = jobs_ul.find_all('li', recursive=False)
return job_li_list
def is_in_masterlist(company_id: str = None, company_name: str = None, company_row: pd.Series = None) -> bool:
if os.path.isfile(f'{BASE_DIR}{COMPANIES_MASTERLIST}'):
masterfile_df = pd.read_csv(f'{BASE_DIR}{COMPANIES_MASTERLIST}')
if company_id is not None and company_id in masterfile_df['COMPANY_ID'].to_list():
return True
elif company_name is not None and company_name in masterfile_df['COMPANY_NAME'].to_list():
return True
elif isinstance(company_row, pd.Series):
if 'COMPANY_ID' in company_row:
if company_row['COMPANY_ID'] in masterfile_df['COMPANY_ID'].to_list():
return True
return False
def open_jobs_page(browser: Browser, company_id: int, location: str = DEFAULT_LOCATION, keyword:str = None) -> None:
if location is None:
location = 'worldwide'
url = f'https://www.linkedin.com/jobs/search?f_C={company_id}&location={location.replace(' ', '%20')}'
if keyword is not None:
url += f'&keywords={keyword}'
browser.open_page(url)
browser.sleep(2)
reject_login(browser)
reject_cookies(browser)
reject_popup(browser)
def parse_recruiter_interests(filepath: str = None) -> None:
company_files = []
if filepath is not None:
company_files.append(filepath)
else:
dir_path = f'{BASE_DIR}{RAW_RECRUITER_INTERESTS_DIR}'
company_files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if isfile(os.path.join(dir_path, f))]
for file in company_files:
print(f'Processing file: {file}')
with open(file, encoding='utf8') as f:
soup = bs(f, 'html.parser')
try:
recruiter = soup.find('div', {'class': 'artdeco-entity-lockup__title ember-view'}).text
recruiter = recruiter.strip()
recruiter = recruiter.replace(' ', '_')
recruiter = re.sub('[^A-Za-z0-9_]+', '', recruiter)
recruiter = re.sub('_+', '_', recruiter)
print(f'Processing interests of {recruiter}')
companies = soup.find_all('div', {'data-view-name': 'profile-component-entity'})
companies_data = []
for company in companies:
url = company.find('a', {'data-field': 'active_tab_companies_interests'})
if url is not None:
url = url['href']
company_id = url.split('/')[-2]
company_name = company.find('span', {'class': 'visually-hidden'}).text.strip()
companies_data.append({'COMPANY_ID': company_id, 'COMPANY_NAME': company_name})
companies_df = pd.DataFrame(companies_data)
companies_df['COMPANY_ID'] = companies_df['COMPANY_ID'].astype('Int64')
companies_df.to_csv(
f'{BASE_DIR}{RECRUITER_COMPANIES_LIST_DIR}{recruiter}.csv',
index=False,
)
moved_file_name = Path(file).name
os.rename(file, f'{BASE_DIR}{PROCESSED_RECRUITER_INTERESTS_DIR}{moved_file_name}')
except Exception as e:
moved_file_name = Path(file).name
os.rename(file, f'{BASE_DIR}{FAILED_RECRUITER_INTERESTS_DIR}{moved_file_name}')
print('An Exception occured:')
print(e)
print('File saved in failed directory. Check HTML formatting.')
def refresh_masterlist(filedir: str = None) -> None:
if filedir is None:
filedir = f'{BASE_DIR}{ENHANCED_COMPANY_LIST_DIR}'
else:
filedir = f'{BASE_DIR}{filedir}'
if os.path.isfile(f'{BASE_DIR}{COMPANIES_MASTERLIST}'):
masterfile_df = pd.read_csv(f'{BASE_DIR}{COMPANIES_MASTERLIST}')
else:
masterfile_df = pd.DataFrame(
{
'COMPANY_ID': pd.Series(dtype='int'),
'COMPANY_NAME': pd.Series(dtype='str'),
'URL': pd.Series(dtype='str'),
'INDUSTRY': pd.Series(dtype='str'),
'LOCATION': pd.Series(dtype='str'),
'DESCRIPTION': pd.Series(dtype='str'),
}
)
masterfile_company_ids = masterfile_df['COMPANY_ID'].to_list()
company_files = [os.path.join(filedir, f) for f in os.listdir(filedir) if isfile(os.path.join(filedir, f))]
for company_file in company_files:
print(f'Consolidating records from {company_file}')
company_df = pd.read_csv(company_file)
filtered_company_df = company_df[~company_df['COMPANY_ID'].isin(masterfile_company_ids)]
masterfile_df = pd.concat([masterfile_df, filtered_company_df], ignore_index=True, sort=False)
masterfile_company_ids += filtered_company_df['COMPANY_ID'].to_list()
masterfile_df = masterfile_df.sort_values(by= ['COMPANY_ID'])
masterfile_df = masterfile_df.drop_duplicates(subset = 'URL', keep = 'first') # if there are lines with and without COMPANY_ID
masterfile_df['COMPANY_ID'] = masterfile_df['COMPANY_ID'].astype('Int64')
masterfile_df.to_csv(f'{BASE_DIR}{COMPANIES_MASTERLIST}', index=False)
def reject_cookies(browser: Browser) -> None:
reject_btn = browser.get_element(By.XPATH, f"//button[contains(text(), 'Reject')]")
if reject_btn is not None:
browser.click_button(By.XPATH, f"//button[contains(text(), 'Reject')]")
def reject_login(browser: Browser) -> None:
login_overlay = browser.get_element(By.CLASS_NAME, 'contextual-sign-in-modal__modal-dismiss')
if login_overlay is not None:
browser.click_button(By.CLASS_NAME, 'contextual-sign-in-modal__modal-dismiss')
else:
login_overlay = browser.get_element(By.ID, 'base-contextual-sign-in-modal')
if login_overlay is not None:
result = browser.delete_element(By.ID, 'base-contextual-sign-in-modal')
def reject_popup(browser: Browser) -> None:
login_overlay = browser.get_element(By.CLASS_NAME, 'cta-modal__dismiss-btn')
if login_overlay is not None:
browser.click_button(By.CLASS_NAME, 'cta-modal__dismiss-btn')
if __name__ == '__main__':
main()