forked from amanv1906/GENAI-CareerAssistant-Multiagent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
355 lines (308 loc) · 11.3 KB
/
search.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
import aiohttp
import os
import urllib
import asyncio
import requests
from typing import List, Literal, Union, Optional
from asgiref.sync import sync_to_async
from linkedin_api import Linkedin
from bs4 import BeautifulSoup
employment_type_mapping = {
"full-time": "F",
"contract": "C",
"part-time": "P",
"temporary": "T",
"internship": "I",
"volunteer": "V",
"other": "O",
}
experience_type_mapping = {
"internship": "1",
"entry-level": "2",
"associate": "3",
"mid-senior-level": "4",
"director": "5",
"executive": "6",
}
job_type_mapping = {
"onsite": "1",
"remote": "2",
"hybrid": "3",
}
def build_linkedin_job_url(
keywords,
location=None,
employment_type=None,
experience_level=None,
job_type=None,
start=10,
):
base_url = "https://www.linkedin.com/jobs-guest/jobs/api/seeMoreJobPostings/search/"
# Prepare query parameters
query_params = {
"keywords": keywords,
}
if location:
query_params["location"] = location
if employment_type:
if isinstance(employment_type, str):
employment_type = [employment_type]
employment_type = ",".join(employment_type)
query_params["f_WT"] = employment_type
if experience_level:
if isinstance(experience_level, str):
experience_level = [experience_level]
experience_level = ",".join(experience_level)
query_params["f_E"] = experience_level
if job_type:
if isinstance(job_type, str):
job_type = [job_type]
job_type = ",".join(job_type)
query_params["f_WT"] = job_type
# Build the complete URL
query_string = urllib.parse.urlencode(query_params)
full_url = f"{base_url}?{query_string}&sortBy=R"
return full_url
def validate_job_search_params(agent_input: Union[str, list], value_dict_mapping: dict):
if isinstance(agent_input, list):
for i, input_str in enumerate(agent_input.copy()):
if not value_dict_mapping.get(input_str):
agent_input.pop(i)
elif isinstance(agent_input, str) and not value_dict_mapping.get(agent_input):
agent_input = None
else:
agent_input = None
return agent_input
def get_job_ids_from_linkedin_api(
keywords: str,
location_name: str,
employment_type=None,
limit: Optional[int] = 5,
job_type=None,
experience=None,
listed_at=86400,
distance=None,
):
try:
job_type = validate_job_search_params(job_type, job_type_mapping)
employment_type = validate_job_search_params(
employment_type, employment_type_mapping
)
experience_level = validate_job_search_params(
experience, experience_type_mapping
)
api = Linkedin(os.getenv("LINKEDIN_EMAIL"), os.getenv("LINKEDIN_PASS"))
job_postings = api.search_jobs(
keywords=keywords,
job_type=employment_type,
location_name=location_name,
remote=job_type,
limit=limit,
experience=experience_level,
listed_at=listed_at,
distance=distance,
)
# Extracting just the part after "jobPosting:" from the trackingUrn and the title using list comprehension
job_ids = [job["trackingUrn"].split("jobPosting:")[1] for job in job_postings]
return job_ids
except Exception as e:
print(f"Error in fetching job ids from LinkedIn API -> {e}")
return []
def get_job_ids(
keywords: str,
location_name: str,
employment_type: Optional[
List[
Literal[
"full-time",
"contract",
"part-time",
"temporary",
"internship",
"volunteer",
"other",
]
]
] = None,
limit: Optional[int] = 10,
job_type: Optional[List[Literal["onsite", "remote", "hybrid"]]] = None,
experience: Optional[
List[
Literal[
"internship",
"entry level",
"associate",
"mid-senior level",
"director",
"executive",
]
]
] = None,
listed_at: Optional[Union[int, str]] = 86400,
distance=None,
):
if os.environ.get("LINKEDIN_SEARCH") == "linkedin_api":
return get_job_ids_from_linkedin_api(
keywords=keywords,
location_name=location_name,
employment_type=employment_type,
limit=limit,
job_type=job_type,
experience=experience,
listed_at=listed_at,
distance=distance,
)
try:
# Construct the URL for LinkedIn job search
job_url = build_linkedin_job_url(
keywords=keywords,
location=location_name,
employment_type=employment_type,
experience_level=experience,
job_type=job_type,
)
# Send a GET request to the URL and store the response
response = requests.get(
job_url, timeout=30, headers={"User-Agent": "Mozilla/5.0"}
)
# Get the HTML, parse the response and find all list items(jobs postings)
list_data = response.text
list_soup = BeautifulSoup(list_data, "html.parser")
page_jobs = list_soup.find_all("li")
# Create an empty list to store the job postings
job_ids = []
# Itetrate through job postings to find job ids
for job in page_jobs:
base_card_div = job.find("div", {"class": "base-card"})
job_id = base_card_div.get("data-entity-urn").split(":")[3]
job_ids.append(job_id)
return job_ids
except Exception as e:
print(f"Error in fetching job ids from LinkedIn -> {e}")
return []
async def fetch_job_details(session, job_id):
# Construct the URL for each job using the job ID
job_url = f"https://www.linkedin.com/jobs-guest/jobs/api/jobPosting/{job_id}"
# Send a GET request to the job URL
async with session.get(job_url) as response:
job_soup = BeautifulSoup(await response.text(), "html.parser")
# Create a dictionary to store job details
job_post = {}
# Try to extract and store the job title
try:
job_post["job_title"] = job_soup.find(
"h2",
{
"class": "top-card-layout__title font-sans text-lg papabear:text-xl font-bold leading-open text-color-text mb-0 topcard__title"
},
).text.strip()
except Exception as exc:
job_post["job_title"] = ""
try:
job_post["job_location"] = job_soup.find(
"span",
{"class": "topcard__flavor topcard__flavor--bullet"},
).text.strip()
except Exception as exc:
job_post["job_location"] = ""
# Try to extract and store the company name
try:
job_post["company_name"] = job_soup.find(
"a", {"class": "topcard__org-name-link topcard__flavor--black-link"}
).text.strip()
except Exception as exc:
job_post["company_name"] = ""
# Try to extract and store the time posted
try:
job_post["time_posted"] = job_soup.find(
"span", {"class": "posted-time-ago__text topcard__flavor--metadata"}
).text.strip()
except Exception as exc:
job_post["time_posted"] = ""
# Try to extract and store the number of applicants
try:
job_post["num_applicants"] = job_soup.find(
"span",
{
"class": "num-applicants__caption topcard__flavor--metadata topcard__flavor--bullet"
},
).text.strip()
except Exception as exc:
job_post["num_applicants"] = ""
# Try to extract and store the job description
try:
job_description = job_soup.find(
"div", {"class": "decorated-job-posting__details"}
).text.strip()
job_post["job_desc_text"] = job_description
except Exception as exc:
job_post["job_desc_text"] = ""
try:
# Try to extract and store the apply link
apply_link_tag = job_soup.find("a", class_="topcard__link")
if apply_link_tag:
apply_link = apply_link_tag.get("href")
job_post["apply_link"] = apply_link
except Exception as exc:
job_post["apply_link"] = ""
return job_post
async def get_job_details_from_linkedin_api(job_id):
try:
api = Linkedin(os.getenv("LINKEDIN_EMAIL"), os.getenv("LINKEDIN_PASS"))
job_data = await sync_to_async(api.get_job)(
job_id
) # Assuming this function is async and fetches job data
# Construct the job data dictionary with defaults
job_data_dict = {
"company_name": job_data.get("companyDetails", {})
.get(
"com.linkedin.voyager.deco.jobs.web.shared.WebCompactJobPostingCompany",
{},
)
.get("companyResolutionResult", {})
.get("name", ""),
"company_url": job_data.get("companyDetails", {})
.get(
"com.linkedin.voyager.deco.jobs.web.shared.WebCompactJobPostingCompany",
{},
)
.get("companyResolutionResult", {})
.get("url", ""),
"job_desc_text": job_data.get("description", {}).get("text", ""),
"work_remote_allowed": job_data.get("workRemoteAllowed", ""),
"job_title": job_data.get("title", ""),
"company_apply_url": job_data.get("applyMethod", {})
.get("com.linkedin.voyager.jobs.OffsiteApply", {})
.get("companyApplyUrl", ""),
"job_location": job_data.get("formattedLocation", ""),
}
except Exception as e:
# Handle exceptions or errors in fetching or parsing the job data
job_data_dict = {
"company_name": "",
"company_url": "",
"job_desc_text": "",
"work_remote_allowed": "",
"job_title": "",
"apply_link": "",
"job_location": "",
}
return job_data_dict
async def fetch_all_jobs(job_ids, batch_size=5):
results = []
try:
if os.environ.get("LINKEDIN_SEARCH") == "linkedin_api":
return await asyncio.gather(
*[get_job_details_from_linkedin_api(job_id) for job_id in job_ids]
)
async with aiohttp.ClientSession() as session:
tasks = []
for job_id in job_ids:
task = asyncio.create_task(fetch_job_details(session, job_id))
tasks.append(task)
# Await the completion of all tasks
results = await asyncio.gather(*tasks)
return results
except Exception as exc:
print(f"Error in fetching job details -> {exc}")
return results