jobstreaming 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ from jobstreaming.api import (
2
+ build_search_request,
3
+ scrape_jobs,
4
+ stream_jobs,
5
+ stream_search,
6
+ )
7
+ from jobstreaming.checkpoint import (
8
+ CheckpointError,
9
+ CheckpointMismatchError,
10
+ JsonFileCheckpointStore,
11
+ MemoryCheckpointStore,
12
+ )
13
+ from jobstreaming.events import (
14
+ AdapterCheckpoint,
15
+ ErrorEvent,
16
+ EventType,
17
+ JobEvent,
18
+ ProgressEvent,
19
+ SearchCheckpoint,
20
+ SearchCompleteEvent,
21
+ SiteCompleteEvent,
22
+ WarningEvent,
23
+ )
24
+ from jobstreaming.model import (
25
+ AdapterCapabilities,
26
+ Compensation,
27
+ CompensationInterval,
28
+ Country,
29
+ DescriptionFormat,
30
+ JobPost,
31
+ JobResponse,
32
+ JobType,
33
+ Location,
34
+ SalarySource,
35
+ Scraper,
36
+ ScraperInput,
37
+ SearchRequest,
38
+ Site,
39
+ )
40
+ from jobstreaming.registry import AdapterRegistry, default_registry
41
+ from jobstreaming.runtime import ScrapeContext, SearchStream
42
+
43
+ __all__ = [
44
+ "AdapterCapabilities",
45
+ "AdapterCheckpoint",
46
+ "AdapterRegistry",
47
+ "CheckpointError",
48
+ "CheckpointMismatchError",
49
+ "Compensation",
50
+ "CompensationInterval",
51
+ "Country",
52
+ "DescriptionFormat",
53
+ "ErrorEvent",
54
+ "EventType",
55
+ "JobEvent",
56
+ "JobPost",
57
+ "JobResponse",
58
+ "JobType",
59
+ "JsonFileCheckpointStore",
60
+ "Location",
61
+ "MemoryCheckpointStore",
62
+ "ProgressEvent",
63
+ "SalarySource",
64
+ "ScrapeContext",
65
+ "Scraper",
66
+ "ScraperInput",
67
+ "SearchCheckpoint",
68
+ "SearchCompleteEvent",
69
+ "SearchRequest",
70
+ "SearchStream",
71
+ "Site",
72
+ "SiteCompleteEvent",
73
+ "WarningEvent",
74
+ "build_search_request",
75
+ "default_registry",
76
+ "scrape_jobs",
77
+ "stream_jobs",
78
+ "stream_search",
79
+ ]
jobstreaming/api.py ADDED
@@ -0,0 +1,224 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+
9
+ from jobstreaming.checkpoint import CheckpointStore, JsonFileCheckpointStore
10
+ from jobstreaming.events import ErrorEvent, JobEvent
11
+ from jobstreaming.model import (
12
+ Country,
13
+ DescriptionFormat,
14
+ JobPost,
15
+ JobType,
16
+ SearchRequest,
17
+ Site,
18
+ )
19
+ from jobstreaming.registry import AdapterRegistry, default_registry
20
+ from jobstreaming.result import jobs_to_dataframe
21
+ from jobstreaming.runtime import SearchStream
22
+ from jobstreaming.util import create_logger, set_logger_level
23
+
24
+
25
+ def _parse_sites(
26
+ site_name: str | Site | list[str | Site] | tuple[str | Site, ...] | None,
27
+ ) -> tuple[Site, ...]:
28
+ if site_name is None:
29
+ return tuple(Site)
30
+ raw_sites = site_name if isinstance(site_name, (list, tuple)) else (site_name,)
31
+ return tuple(
32
+ Site.from_string(site) if isinstance(site, str) else site for site in raw_sites
33
+ )
34
+
35
+
36
+ def build_search_request(
37
+ *,
38
+ site_name: str | Site | list[str | Site] | tuple[str | Site, ...] | None = None,
39
+ search_term: str | None = None,
40
+ google_search_term: str | None = None,
41
+ location: str | None = None,
42
+ distance: int = 50,
43
+ is_remote: bool = False,
44
+ job_type: str | JobType | None = None,
45
+ easy_apply: bool | None = None,
46
+ results_wanted: int = 15,
47
+ country_indeed: str | Country = Country.USA,
48
+ description_format: str | DescriptionFormat = DescriptionFormat.MARKDOWN,
49
+ linkedin_fetch_description: bool = False,
50
+ linkedin_company_ids: list[int] | tuple[int, ...] | None = None,
51
+ offset: int = 0,
52
+ hours_old: int | None = None,
53
+ enforce_annual_salary: bool = False,
54
+ request_timeout: float = 30,
55
+ max_pages: int = 50,
56
+ ) -> SearchRequest:
57
+ parsed_job_type = (
58
+ JobType.from_string(job_type) if isinstance(job_type, str) else job_type
59
+ )
60
+ country = (
61
+ Country.from_string(country_indeed)
62
+ if isinstance(country_indeed, str)
63
+ else country_indeed
64
+ )
65
+ return SearchRequest(
66
+ site_type=_parse_sites(site_name),
67
+ country=country,
68
+ search_term=search_term,
69
+ google_search_term=google_search_term,
70
+ location=location,
71
+ distance=distance,
72
+ is_remote=is_remote,
73
+ job_type=parsed_job_type,
74
+ easy_apply=easy_apply,
75
+ description_format=description_format,
76
+ linkedin_fetch_description=linkedin_fetch_description,
77
+ results_wanted=results_wanted,
78
+ linkedin_company_ids=linkedin_company_ids,
79
+ offset=offset,
80
+ hours_old=hours_old,
81
+ enforce_annual_salary=enforce_annual_salary,
82
+ request_timeout=request_timeout,
83
+ max_pages=max_pages,
84
+ )
85
+
86
+
87
+ def stream_search(
88
+ request: SearchRequest | None = None,
89
+ *,
90
+ registry: AdapterRegistry | None = None,
91
+ checkpoint_store: CheckpointStore | None = None,
92
+ checkpoint_path: str | Path | None = None,
93
+ resume: bool = True,
94
+ proxies: list[str] | str | None = None,
95
+ ca_cert: str | None = None,
96
+ user_agent: str | None = None,
97
+ queue_size: int = 128,
98
+ max_retries: int = 1,
99
+ retry_backoff: float = 0.5,
100
+ **search_options: Any,
101
+ ) -> SearchStream:
102
+ if request is not None and search_options:
103
+ options = ", ".join(sorted(search_options))
104
+ raise TypeError(
105
+ f"Cannot combine a SearchRequest with legacy search options: {options}"
106
+ )
107
+ if request is None:
108
+ request = build_search_request(**search_options)
109
+ if checkpoint_store is not None and checkpoint_path is not None:
110
+ raise ValueError("Use checkpoint_store or checkpoint_path, not both")
111
+ if checkpoint_path is not None:
112
+ checkpoint_store = JsonFileCheckpointStore(checkpoint_path)
113
+ return SearchStream(
114
+ request,
115
+ registry=registry or default_registry(),
116
+ checkpoint_store=checkpoint_store,
117
+ resume=resume,
118
+ proxies=proxies,
119
+ ca_cert=ca_cert,
120
+ user_agent=user_agent,
121
+ queue_size=queue_size,
122
+ max_retries=max_retries,
123
+ retry_backoff=retry_backoff,
124
+ )
125
+
126
+
127
+ def stream_jobs(
128
+ request: SearchRequest | None = None,
129
+ *,
130
+ raise_on_error: bool = False,
131
+ **stream_options: Any,
132
+ ) -> Iterator[JobPost]:
133
+ with stream_search(request, **stream_options) as stream:
134
+ for event in stream:
135
+ if isinstance(event, JobEvent):
136
+ yield event.job
137
+ elif isinstance(event, ErrorEvent) and raise_on_error:
138
+ raise RuntimeError(
139
+ f"{event.site.value} failed: {event.error_type}: {event.message}"
140
+ )
141
+
142
+
143
+ def scrape_jobs(
144
+ site_name: str | Site | list[str | Site] | None = None,
145
+ search_term: str | None = None,
146
+ google_search_term: str | None = None,
147
+ location: str | None = None,
148
+ distance: int = 50,
149
+ is_remote: bool = False,
150
+ job_type: str | JobType | None = None,
151
+ easy_apply: bool | None = None,
152
+ results_wanted: int = 15,
153
+ country_indeed: str | Country = Country.USA,
154
+ proxies: list[str] | str | None = None,
155
+ ca_cert: str | None = None,
156
+ description_format: str | DescriptionFormat = DescriptionFormat.MARKDOWN,
157
+ linkedin_fetch_description: bool = False,
158
+ linkedin_company_ids: list[int] | None = None,
159
+ offset: int = 0,
160
+ hours_old: int | None = None,
161
+ enforce_annual_salary: bool = False,
162
+ verbose: int = 0,
163
+ user_agent: str | None = None,
164
+ *,
165
+ request_timeout: float = 30,
166
+ max_pages: int = 50,
167
+ checkpoint_store: CheckpointStore | None = None,
168
+ checkpoint_path: str | Path | None = None,
169
+ resume: bool = True,
170
+ registry: AdapterRegistry | None = None,
171
+ raise_on_error: bool = False,
172
+ max_retries: int = 1,
173
+ retry_backoff: float = 0.5,
174
+ ) -> pd.DataFrame:
175
+ set_logger_level(verbose)
176
+ request = build_search_request(
177
+ site_name=site_name,
178
+ search_term=search_term,
179
+ google_search_term=google_search_term,
180
+ location=location,
181
+ distance=distance,
182
+ is_remote=is_remote,
183
+ job_type=job_type,
184
+ easy_apply=easy_apply,
185
+ results_wanted=results_wanted,
186
+ country_indeed=country_indeed,
187
+ description_format=description_format,
188
+ linkedin_fetch_description=linkedin_fetch_description,
189
+ linkedin_company_ids=linkedin_company_ids,
190
+ offset=offset,
191
+ hours_old=hours_old,
192
+ enforce_annual_salary=enforce_annual_salary,
193
+ request_timeout=request_timeout,
194
+ max_pages=max_pages,
195
+ )
196
+ jobs: list[tuple[Site, JobPost]] = []
197
+ errors: list[ErrorEvent] = []
198
+ with stream_search(
199
+ request,
200
+ registry=registry,
201
+ checkpoint_store=checkpoint_store,
202
+ checkpoint_path=checkpoint_path,
203
+ resume=resume,
204
+ proxies=proxies,
205
+ ca_cert=ca_cert,
206
+ user_agent=user_agent,
207
+ max_retries=max_retries,
208
+ retry_backoff=retry_backoff,
209
+ ) as stream:
210
+ for event in stream:
211
+ if isinstance(event, JobEvent):
212
+ jobs.append((event.site, event.job))
213
+ elif isinstance(event, ErrorEvent):
214
+ errors.append(event)
215
+ create_logger(event.site.value).error(
216
+ "%s: %s", event.error_type, event.message
217
+ )
218
+
219
+ if errors and raise_on_error:
220
+ first = errors[0]
221
+ raise RuntimeError(
222
+ f"{first.site.value} failed: {first.error_type}: {first.message}"
223
+ )
224
+ return jobs_to_dataframe(jobs, request)
@@ -0,0 +1,188 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from urllib.parse import quote, urljoin
5
+
6
+ from bs4 import BeautifulSoup
7
+
8
+ from jobstreaming.model import (
9
+ AdapterCapabilities,
10
+ Country,
11
+ JobPost,
12
+ JobResponse,
13
+ Location,
14
+ Scraper,
15
+ ScraperInput,
16
+ Site,
17
+ )
18
+ from jobstreaming.runtime import ScrapeContext
19
+ from jobstreaming.util import create_logger, create_session, stable_job_id
20
+
21
+ log = create_logger("Bayt")
22
+
23
+
24
+ class BaytScraper(Scraper):
25
+ capabilities = AdapterCapabilities(
26
+ filters=frozenset({"offset"}),
27
+ supports_resume=True,
28
+ resume_granularity="page",
29
+ )
30
+ base_url = "https://www.bayt.com"
31
+ delay = 2
32
+ band_delay = 3
33
+
34
+ def __init__(
35
+ self,
36
+ proxies: list[str] | str | None = None,
37
+ ca_cert: str | None = None,
38
+ user_agent: str | None = None,
39
+ ):
40
+ super().__init__(
41
+ Site.BAYT,
42
+ proxies=proxies,
43
+ ca_cert=ca_cert,
44
+ user_agent=user_agent,
45
+ )
46
+ self.scraper_input = None
47
+ self.session = None
48
+ self.country = "worldwide"
49
+
50
+ def scrape(
51
+ self, scraper_input: ScraperInput, context: ScrapeContext | None = None
52
+ ) -> JobResponse:
53
+ self.scraper_input = scraper_input
54
+ context = ScrapeContext.local(self.site, scraper_input, context)
55
+ self.session = create_session(
56
+ proxies=self.proxies, ca_cert=self.ca_cert, is_tls=False, has_retry=True
57
+ )
58
+ if self.user_agent:
59
+ self.session.headers.update({"user-agent": self.user_agent})
60
+ job_list: list[JobPost] = []
61
+ state = context.resume_state
62
+ page = int(state.get("page", 1))
63
+ page_skip = int(state.get("page_skip", 0))
64
+ raw_seen = int(state.get("raw_seen", 0))
65
+
66
+ while context.should_continue and page <= scraper_input.max_pages:
67
+ log.info(f"Fetching Bayt jobs page {page}")
68
+ job_elements = self._fetch_jobs(self.scraper_input.search_term, page)
69
+ if not job_elements:
70
+ break
71
+
72
+ if job_elements:
73
+ log.debug(
74
+ "First job element snippet:\n" + job_elements[0].prettify()[:500]
75
+ )
76
+
77
+ page_raw_start = max(0, raw_seen - page_skip)
78
+ for index, job in enumerate(job_elements):
79
+ absolute_index = page_raw_start + index
80
+ try:
81
+ job_post = self._extract_job_info(job)
82
+ if job_post and absolute_index >= scraper_input.offset:
83
+ next_state = {
84
+ "page": page,
85
+ "page_skip": index + 1,
86
+ "raw_seen": absolute_index + 1,
87
+ }
88
+ if context.emit_job(job_post, next_state):
89
+ job_list.append(job_post)
90
+ if not context.should_continue:
91
+ break
92
+ if not job_post:
93
+ log.debug(
94
+ "Extraction returned None. Job snippet:\n"
95
+ + job.prettify()[:500]
96
+ )
97
+ except Exception as e:
98
+ context.emit_warning(
99
+ f"Skipped Bayt listing: {type(e).__name__}: {e}"
100
+ )
101
+ continue
102
+
103
+ raw_seen = page_raw_start + len(job_elements)
104
+ context.emit_progress(
105
+ {"page": page + 1, "page_skip": 0, "raw_seen": raw_seen},
106
+ f"completed Bayt page {page}",
107
+ )
108
+ if not context.should_continue:
109
+ break
110
+ page += 1
111
+ page_skip = 0
112
+ if not context.wait(
113
+ random.uniform(self.delay, self.delay + self.band_delay)
114
+ ):
115
+ break
116
+
117
+ return JobResponse(jobs=job_list)
118
+
119
+ def _fetch_jobs(self, query: str | None, page: int) -> list:
120
+ """
121
+ Grabs the job results for the given query and page number.
122
+ """
123
+ encoded_query = quote((query or "").strip(), safe="")
124
+ url = f"{self.base_url}/en/international/jobs/{encoded_query}-jobs/?page={page}"
125
+ response = self.session.get(url, timeout=self.scraper_input.request_timeout)
126
+ response.raise_for_status()
127
+ soup = BeautifulSoup(response.text, "html.parser")
128
+ job_listings = soup.find_all("li", attrs={"data-js-job": ""})
129
+ log.debug(f"Found {len(job_listings)} job listing elements")
130
+ return job_listings
131
+
132
+ def _extract_job_info(self, job: BeautifulSoup) -> JobPost | None:
133
+ """
134
+ Extracts the job information from a single job listing.
135
+ """
136
+ # Find the h2 element holding the title and link (no class filtering)
137
+ job_general_information = job.find("h2")
138
+ if not job_general_information:
139
+ return
140
+
141
+ job_title = job_general_information.get_text(strip=True)
142
+ job_url = self._extract_job_url(job_general_information)
143
+ if not job_url:
144
+ return
145
+
146
+ # Extract company name using the original approach:
147
+ company_tag = job.find("div", class_="t-nowrap p10l")
148
+ company_name = (
149
+ company_tag.find("span").get_text(strip=True)
150
+ if company_tag and company_tag.find("span")
151
+ else None
152
+ )
153
+
154
+ # Extract location using the original approach:
155
+ location_tag = job.find("div", class_="t-mute t-small")
156
+ location = location_tag.get_text(strip=True) if location_tag else None
157
+
158
+ job_id = stable_job_id("bayt", job_url)
159
+ location_parts = [part.strip() for part in (location or "").split(",")]
160
+ location_parts = [part for part in location_parts if part]
161
+ location_obj = (
162
+ Location(
163
+ city=location_parts[0] if location_parts else None,
164
+ state=(
165
+ ", ".join(location_parts[1:-1]) if len(location_parts) > 2 else None
166
+ ),
167
+ country=(
168
+ location_parts[-1] if len(location_parts) > 1 else Country.WORLDWIDE
169
+ ),
170
+ )
171
+ if location_parts
172
+ else None
173
+ )
174
+ return JobPost(
175
+ id=job_id,
176
+ title=job_title,
177
+ company_name=company_name,
178
+ location=location_obj,
179
+ job_url=job_url,
180
+ )
181
+
182
+ def _extract_job_url(self, job_general_information: BeautifulSoup) -> str | None:
183
+ """
184
+ Pulls the job URL from the 'a' within the h2 element.
185
+ """
186
+ a_tag = job_general_information.find("a")
187
+ if a_tag and a_tag.has_attr("href"):
188
+ return urljoin(self.base_url, a_tag["href"].strip())