返回 last30days-skill
talentbrew.py
根目录 / skills / last30days / scripts / lib / job_boards / talentbrew.py
1 """TalentBrew (Radancy): the job search's own results call.
2
3 The search page asks ``/search-jobs/results`` with ``X-Requested-With:
4 XMLHttpRequest`` for each page of results; the answer is JSON whose
5 ``results`` value is the HTML list it shows, with the total in
6 ``data-total-results``. Each result is a link to the role's page with its
7 title, location and posted date in classed spans. A role's page carries a
8 schema.org ``JobPosting`` with the full text.
9 """
10
11 from __future__ import annotations
12
13 import re
14 import time
15 from typing import Any, Callable
16 from urllib.parse import urljoin, urlparse
17
18 from .. import http, jobs
19 from . import detect
20 from .detect import PROVIDER_TALENTBREW
21
22 PAGE_SIZE = 100
23 _TOTAL_RE = re.compile(r'data-total-results\s*=\s*["\']?(\d+)', re.I)
24 _TOKEN_RE = re.compile(r"<(/?)(ul|ol|li|a|span)\b([^<>]*)>", re.I)
25 _TOKEN_NO_SPAN_RE = re.compile(r"<(/?)(ul|ol|li|a)\b([^<>]*)>", re.I)
26
27
28 def _extract_entries(html: str) -> tuple[list[dict[str, str]], int | None]:
29 """Single-pass linear tokenizer for TalentBrew results HTML, supporting
30 both nested ``<ul>``/``<ol>`` lists and omitted optional ``</li>`` end tags."""
31 if not html:
32 return [], None
33 bounded = html[:detect.MAX_HTML_CHARS]
34 total_match = _TOTAL_RE.search(bounded)
35 total = int(total_match.group(1)) if total_match else None
36 lowered = bounded.lower()
37 if "/job/" not in bounded or "<li" not in lowered or "</a" not in lowered:
38 return [], total
39 token_re = _TOKEN_RE if "</span" in lowered else _TOKEN_NO_SPAN_RE
40 entries: list[dict[str, str]] = []
41 list_depth = 0
42 outer_list_depth: int | None = None
43 current: dict[str, str] | None = None
44 link_depth = 0
45 link_start = 0
46 span_kind = ""
47 span_depth = 0
48 span_start = 0
49
50 def flush_current() -> None:
51 nonlocal current, outer_list_depth, link_depth, span_kind, span_depth
52 if current is not None:
53 if current["href"] and current["title"]:
54 entries.append(current)
55 current = None
56 outer_list_depth = None
57 link_depth = 0
58 span_kind = ""
59 span_depth = 0
60
61 for match in token_re.finditer(bounded):
62 closing = bool(match.group(1))
63 tag = match.group(2).lower()
64 if tag in ("ul", "ol"):
65 if not closing:
66 list_depth += 1
67 else:
68 if current is not None and outer_list_depth is not None and list_depth <= outer_list_depth:
69 flush_current()
70 if list_depth > 0:
71 list_depth -= 1
72 continue
73 if tag == "li":
74 if not closing:
75 if current is None:
76 current = {"href": "", "title": "", "location": "", "date": ""}
77 outer_list_depth = list_depth
78 elif outer_list_depth == list_depth:
79 flush_current()
80 current = {"href": "", "title": "", "location": "", "date": ""}
81 outer_list_depth = list_depth
82 elif current is not None and outer_list_depth == list_depth:
83 flush_current()
84 continue
85 if current is None:
86 continue
87 if tag == "a":
88 if not closing:
89 if link_depth > 0:
90 link_depth += 1
91 elif not current["href"]:
92 raw_attrs = match.group(3)
93 if "/job/" in raw_attrs:
94 href = detect.parse_html_attrs(raw_attrs).get("href", "").strip()
95 if (
96 href.startswith("/job/")
97 and not href.startswith("//")
98 and not detect._UNSAFE_URL_CHAR_RE.search(href)
99 ):
100 current["href"] = href
101 link_depth = 1
102 link_start = match.end()
103 elif link_depth > 0:
104 link_depth -= 1
105 if link_depth == 0 and not current["title"]:
106 current["title"] = jobs._clean_html(bounded[link_start:match.start()])
107 elif tag == "span":
108 if not closing:
109 if span_depth > 0:
110 span_depth += 1
111 else:
112 raw_attrs = match.group(3)
113 raw_lower = raw_attrs.lower()
114 if (
115 (not current["location"] and "location" in raw_lower)
116 or (not current["date"] and "date" in raw_lower)
117 ):
118 classes = detect.parse_html_attrs(raw_attrs).get("class", "").lower()
119 if "location" in classes and not current["location"]:
120 span_kind = "location"
121 span_depth = 1
122 span_start = match.end()
123 elif "date" in classes and not current["date"]:
124 span_kind = "date"
125 span_depth = 1
126 span_start = match.end()
127 elif span_depth > 0:
128 span_depth -= 1
129 if span_depth == 0 and span_kind:
130 current[span_kind] = jobs._clean_html(bounded[span_start:match.start()])
131 span_kind = ""
132 flush_current()
133 return entries, total
134
135
136 def listing_url(entry: dict[str, Any], page: int = 1) -> str:
137 return (
138 f"https://{entry['board']}/search-jobs/results?ActiveFacetID=0"
139 f"&CurrentPage={page}&RecordsPerPage={PAGE_SIZE}&SortCriteria=1&SortDirection=1"
140 "&SearchResultsModuleName=Search+Results&SearchFiltersModuleName=Search+Filters"
141 )
142
143
144 def _us_date(text: str) -> str | None:
145 try:
146 return time.strftime("%Y-%m-%d", time.strptime(text.strip(), "%m/%d/%Y"))
147 except ValueError:
148 return None
149
150
151 def parse_listing(payload: Any, entry: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:
152 html = payload.get("results") if isinstance(payload, dict) else None
153 if not isinstance(html, str):
154 raise jobs.BoardShapeError("no results HTML")
155 raw_entries, total = _extract_entries(html)
156 board = str(entry["board"]).strip().rstrip(".").lower()
157 base = f"https://{board}/"
158 items: list[dict[str, Any]] = []
159 seen: set[str] = set()
160 for row in raw_entries:
161 title = row["title"]
162 if not title:
163 continue
164 url = urljoin(base, row["href"])
165 if url in seen:
166 continue
167 parsed = urlparse(url)
168 if (
169 parsed.scheme.lower() != "https"
170 or detect.page_host(url) != board
171 or parsed.port is not None
172 ):
173 continue
174 seen.add(url)
175 location = row["location"]
176 posted = _us_date(row["date"]) if row["date"] else None
177 items.append(jobs._ats_item(
178 provider=PROVIDER_TALENTBREW,
179 slug=entry["board"],
180 ident=url.rstrip("/").rsplit("/", 1)[-1],
181 title=title,
182 url=url,
183 description="",
184 date=posted,
185 posted_date_true=bool(posted),
186 department="",
187 location=location,
188 company_name=str(entry.get("name") or ""),
189 whole_posting=True,
190 ))
191 return items, total if total is not None else len(items)
192
193
194 def read_board(
195 entry: dict[str, Any], *, deadline: float, date_range: tuple[str, str],
196 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
197 """The board in the search's own order, with the total it reports. The
198 order is not shown to be by date, so the read is not newest first."""
199
200 def page(offset: int) -> Callable[[float], Any]:
201 url = listing_url(entry, offset // PAGE_SIZE + 1)
202
203 def fetch(http_deadline: float) -> Any:
204 if not detect.is_safe_public_url(url):
205 raise http.HTTPError("Refused non-public URL")
206 return http.get(
207 url, headers={"Accept": "application/json", "X-Requested-With": "XMLHttpRequest"},
208 timeout=jobs.API_TIMEOUT_SECONDS, retries=2, deadline_monotonic=http_deadline,
209 public_only=True, redirect_guard=detect.same_site_redirect_guard(url),
210 )
211
212 return fetch
213
214 return jobs._read_newest_first(
215 page, lambda payload: parse_listing(payload, entry), page_size=PAGE_SIZE,
216 row_ceiling=jobs.COMPANY_BOARD_ROW_CEILING, window_start=date_range[0],
217 deadline=deadline, newest_first=False,
218 )
219
220
221 def fetch_details(items: list[dict[str, Any]], *, deadline: float) -> tuple[int, int]:
222 """Fill the full text of the given roles from the JobPosting on their pages."""
223
224 def call(item: dict[str, Any]) -> Callable[[float], Any]:
225 url = str(item.get("url") or "")
226 if not detect.is_safe_public_url(url):
227 return lambda _http_deadline: None
228 return lambda http_deadline: jobs.role_page_text(
229 url, timeout=jobs.API_TIMEOUT_SECONDS, deadline_monotonic=http_deadline,
230 redirect_guard=detect.same_site_redirect_guard(url),
231 )
232
233 return jobs._fill_role_text(items, call, jobs.jsonld_role_text, deadline=deadline)
234
234 lines PYTHON