返回 last30days-skill
sitemap.py
根目录 / skills / last30days / scripts / lib / job_boards / sitemap.py
1 """The roster tier: a careers site's job sitemap, when its pages are walled.
2
3 Some careers sites answer every page with a challenge or a block but publish
4 a job sitemap for crawlers, listed in their robots.txt (SAP: ``jobs.sap.com``
5 -> ``sitemap.xml`` index -> ``/en/jobs/sitemap.xml``, one URL per role). The
6 tier reads that list: one role per job URL, its title from the URL's slug.
7 When the URLs carry no title (``/jobs/R-674391``), the first role pages are
8 asked for theirs (``og:title``, a ``JobPosting`` or ``<title>``); a site that
9 walls those too gives a count of roles and no titles.
10
11 A sitemap's ``lastmod`` is when the entry last changed, not when the role was
12 posted, so no row claims a posted date and the board prints no count of roles
13 new in the window. No row has text: the digest built from these rows is
14 titles only, and says so.
15 """
16
17 from __future__ import annotations
18
19 import re
20 import socket # noqa: F401 kept: tests patch name resolution through this module
21 import time
22 import xml.etree.ElementTree as ET
23 from html import unescape
24 from typing import Any, Callable
25 from urllib.parse import urlparse
26
27 from .. import http, jobs, jobs_digest
28 from . import detect, robots
29
30 PROVIDER_SITEMAP = "sitemap"
31 # Sitemap files asked for in all, across indexes, for one site.
32 SITEMAP_FILE_LIMIT = 6
33 # Role pages asked for their title when the URLs carry none.
34 TITLE_PAGE_LIMIT = jobs_digest.DIGEST_MAX_ROLES
35 # Role pages asked first; the rest only when one of these gave a title.
36 TITLE_FIRST_WAVE = 8
37 TIMEOUT_SECONDS = 8
38 MAX_SITEMAP_BYTES = 10 * 1024 * 1024
39 MAX_SITEMAP_CHARS = 10 * 1024 * 1024
40 MAX_PAGE_BYTES = detect.MAX_HTML_BYTES
41 MAX_PAGE_CHARS = detect.MAX_HTML_CHARS
42 _XML_UNSAFE_DECL = re.compile(r"<!(?:DOCTYPE|ENTITY)\b", re.I)
43 # A role's own page: a jobs segment followed by the role's id or slug.
44 _JOB_PATH = re.compile(
45 r"/(?:jobs?|job-detail|positions?|vacanc(?:y|ies)|openings?|requisitions?)/([^?#]+?)/?$", re.I,
46 )
47 _JOBS_WORD = re.compile(r"job|career|position|vacanc|opening", re.I)
48 _LOCALE = re.compile(r"^/[a-z]{2}(?:[-_][A-Za-z]{2})?/")
49 _ID_PART = re.compile(r"^(?:[A-Za-z]{0,4}[-_]?\d[\w-]*|\d+)$")
50
51
52 # A page title a challenge, block or error page gives in place of the role's.
53 _BLOCK_TITLE = re.compile(
54 r"just a moment|attention required|access denied|forbidden|captcha|are you (?:a )?(?:human|robot)"
55 r"|security check|verify(?:ing)? you are|request (?:rejected|blocked)|unusual traffic"
56 r"|page not found|service unavailable|^not found$|^error\b|^(?:40[134]|50[0-9])\b|^sign in|^log ?in$",
57 re.I,
58 )
59
60
61 def _public_url(url: str, host: str) -> bool:
62 """Whether ``url`` is a standard-port http(s) address on the site of ``host``
63 whose host is a public domain name, not an address on a private, loopback,
64 multicast, NAT64 or reserved network.
65
66 A sitemap is remote content: a role URL it lists is fetched only when it
67 stays on the company's own site, so a sitemap cannot point the lane at a
68 service on the user's network.
69 """
70 return detect.public_site_url(url, host, resolves=_resolves_public)
71
72
73 # The bounded-TTL resolver, kept under this module's name so the check above
74 # looks it up here at call time.
75 _resolves_public = detect.resolves_public
76
77
78 def _fetch(url: str, deadline: float) -> str | None:
79 remaining = deadline - jobs._clock()()
80 if remaining <= 0:
81 return None
82 with http.capture_failures():
83 return _on_site(url, lambda landed: jobs.role_page_text(
84 url, timeout=TIMEOUT_SECONDS,
85 deadline_monotonic=time.monotonic() + min(remaining, TIMEOUT_SECONDS), landed=landed,
86 redirect_guard=_guard(url), max_bytes=MAX_SITEMAP_BYTES,
87 ))
88
89
90 def _custom_resolver() -> Callable[[str], bool] | None:
91 return None if _resolves_public is detect.resolves_public else _resolves_public
92
93
94 def _guard(url: str) -> Callable[[str], bool]:
95 """The redirect check for a fetch of ``url``: it may be redirected only to
96 an address on the same site that is not on a private network."""
97 return detect.same_site_redirect_guard(url, resolves=_custom_resolver())
98
99
100 def _on_site(url: str, fetch: Callable[[list], str | None]) -> str | None:
101 """``fetch``'s text, or None when the request was redirected off the
102 site ``url`` is on, downgraded from https to http, or sent to a private
103 address: such a page never enters the report."""
104 host = detect.page_host(url)
105 if not host or not detect.is_safe_public_url(url):
106 return None
107 require_https = urlparse(url).scheme.lower() == "https"
108 landed: list = []
109 text = fetch(landed)
110 if text is not None and landed:
111 final = str(landed[-1])
112 if not detect.is_safe_public_url(final):
113 return None
114 saw_https = require_https or any(
115 detect.is_safe_public_url(str(hop)) and urlparse(str(hop)).scheme.lower() == "https"
116 for hop in landed[:-1]
117 )
118 custom = _custom_resolver()
119 if custom is None:
120 if not detect.is_same_site_public_url(final, host, require_https=saw_https):
121 return None
122 elif not detect.public_site_url(final, host, resolves=custom, require_https=saw_https):
123 return None
124 return text
125
126
127 def _local_tag(tag: Any) -> str:
128 return tag.rsplit("}", 1)[-1].lower() if isinstance(tag, str) else ""
129
130
131 def _parse_sitemap_xml(text: str) -> tuple[str | None, list[tuple[str, str]]]:
132 """Parse a sitemap index or urlset with ElementTree after rejecting DTD/ENTITY.
133
134 Returns ``("sitemapindex", children)``, ``("urlset", entries)``, or
135 ``(None, [])`` when the document is rejected, malformed, or not a sitemap.
136 """
137 if not text or len(text) > MAX_SITEMAP_CHARS or _XML_UNSAFE_DECL.search(text):
138 return None, []
139 cleaned = text.lstrip("\ufeff \t\r\n")
140 if not cleaned:
141 return None, []
142 try:
143 root = ET.fromstring(cleaned)
144 except ET.ParseError:
145 return None, []
146 kind = _local_tag(root.tag)
147 if kind == "sitemapindex":
148 children: list[tuple[str, str]] = []
149 for elem in root:
150 if _local_tag(elem.tag) != "sitemap":
151 continue
152 for sub in elem:
153 if _local_tag(sub.tag) == "loc":
154 loc = (sub.text or "").strip()
155 if loc:
156 children.append((loc, ""))
157 break
158 return "sitemapindex", children
159 if kind == "urlset":
160 entries: list[tuple[str, str]] = []
161 for elem in root:
162 if _local_tag(elem.tag) != "url":
163 continue
164 loc = lastmod = ""
165 for sub in elem:
166 sub_tag = _local_tag(sub.tag)
167 if sub_tag == "loc" and not loc:
168 loc = (sub.text or "").strip()
169 elif sub_tag == "lastmod" and not lastmod:
170 lastmod = (sub.text or "").strip()
171 if loc:
172 entries.append((loc, lastmod))
173 return "urlset", entries
174 return None, []
175
176
177 def _is_jobs_sitemap_url(url: str, jobs_host: bool) -> bool:
178 return bool(jobs_host) or bool(_JOBS_WORD.search(url))
179
180
181 def job_urls(hosts: list[str], *, deadline: float) -> tuple[str, list[tuple[str, str]], bool]:
182 """The host whose sitemaps list job URLs, those URLs with their
183 ``lastmod`` ('' when none), from the first host in ``hosts`` that has any,
184 and whether some of its sitemap files went unread (the file limit, or a
185 file that did not answer), so the count is a floor.
186
187 A role listed under several URLs (one sitemap per language, the same
188 role id in each) counts once.
189
190 A host's robots.txt names its sitemaps. On a jobs or careers host every
191 sitemap is read; on another host (the company's main site) only those
192 whose address names jobs or careers, so a marketing sitemap is not.
193 """
194 for raw_host in hosts:
195 if jobs._clock()() >= deadline:
196 break
197 host = (raw_host or "").strip().rstrip(".").lower()
198 robots_url = f"https://{host}/robots.txt"
199 if not host or not detect.is_safe_public_url(robots_url) or detect.page_host(robots_url) != host:
200 continue
201 rules = robots.rules_for(
202 host, deadline_monotonic=time.monotonic() + max(0.0, deadline - jobs._clock()()),
203 )
204 jobs_host = bool(re.match(r"(?:jobs|careers?)\.", host)) or bool(_JOBS_WORD.search(host.split(".")[0] or ""))
205 queue = [
206 url for url in rules.sitemaps
207 # robots.txt is remote content too: its sitemaps pass the same
208 # check as the role URLs they list.
209 if _public_url(url, host) and _is_jobs_sitemap_url(url, jobs_host)
210 ]
211 found: dict[str, tuple[str, str]] = {}
212 asked = 0
213 missed = False
214 while queue and asked < SITEMAP_FILE_LIMIT:
215 url = queue.pop(0)
216 asked += 1
217 text = _fetch(url, deadline)
218 if not text:
219 # On a jobs host any sitemap file may hold roles
220 # (``sitemap-2.xml``); elsewhere only one that names jobs.
221 missed = missed or _is_jobs_sitemap_url(url, jobs_host)
222 continue
223 xml_kind, entries = _parse_sitemap_xml(text)
224 if not xml_kind:
225 missed = missed or _is_jobs_sitemap_url(url, jobs_host)
226 continue
227 if xml_kind == "sitemapindex":
228 # Screen malformed URLs before urlparse() and sort jobs sitemaps first.
229 children = sorted(
230 (loc for loc, _lastmod in entries if detect.is_safe_public_url(loc)),
231 key=lambda child: (
232 not _JOBS_WORD.search(urlparse(child).path), "/en" not in child,
233 ),
234 )
235 # One file per path across languages: /fr/jobs/sitemap.xml
236 # lists the roles /en/jobs/sitemap.xml does.
237 kept: dict[str, str] = {}
238 for child in children:
239 if _public_url(child, host):
240 kept.setdefault(_LOCALE.sub("/", urlparse(child).path, count=1), child)
241 queue = list(kept.values()) + queue
242 continue
243 for page, lastmod in entries:
244 if not _public_url(page, host):
245 continue
246 key = _role_key(page)
247 if _JOB_PATH.search(urlparse(page).path) and key not in found:
248 found[key] = (page, lastmod)
249 if found:
250 unread = bool(queue) and any(_is_jobs_sitemap_url(url, jobs_host) for url in queue)
251 return host, list(found.values()), missed or unread
252 return "", [], False
253
254
255 def _role_key(url: str) -> str:
256 """What makes two job URLs the same role: the role's id (the longest run
257 of five or more digits in the path), or the URL when it carries none."""
258 ids = re.findall(r"\d{5,}", urlparse(url).path)
259 return max(ids, key=len) if ids else url
260
261
262 def title_from_url(url: str) -> str:
263 """The title a role's URL carries in its slug, or ''."""
264 match = _JOB_PATH.search(urlparse(url).path)
265 if not match:
266 return ""
267 for part in reversed(match.group(1).split("/")):
268 part = re.sub(r"^XMLNAME-", "", part)
269 part = re.sub(r"_[A-Z]*\d[\w-]*$", "", part)
270 words = [word for word in re.split(r"[-_+]+", part) if word]
271 if _ID_PART.match(part) or len(words) < 2 or not any(re.search("[A-Za-z]", w) for w in words):
272 continue
273 return " ".join(word if word.isupper() else word.capitalize() for word in words)
274 return ""
275
276
277 def _clean_page_title(raw: str, site_name: str, *, unescape_entities: bool = False) -> str:
278 text = unescape(raw) if unescape_entities else raw
279 title = " ".join(text.split())
280 parts = re.split(r"\s+[-|–]\s+", title)
281 if len(parts) > 1 and re.search(r"career|job|" + re.escape(site_name or "~"), parts[-1], re.I):
282 title = " - ".join(parts[:-1])
283 if title and not _BLOCK_TITLE.search(title):
284 return title
285 return ""
286
287
288 def title_from_page(html: str, site_name: str = "") -> str:
289 """A role page's own title: its JobPosting, ``og:title`` or ``<title>``,
290 with a trailing site name (`` - Walmart Careers``) cut off."""
291 if not html:
292 return ""
293 bounded = html[:MAX_PAGE_CHARS]
294 for block in detect.extract_jsonld_blocks(bounded):
295 try:
296 nodes = jobs._walk_jsonld(block)
297 except RecursionError:
298 continue
299 for obj in nodes:
300 if isinstance(obj, dict) and jobs._is_job_posting(obj):
301 raw = obj.get("title") or obj.get("name")
302 if isinstance(raw, str) and raw.strip():
303 cleaned = _clean_page_title(raw, site_name, unescape_entities=True)
304 if cleaned:
305 return cleaned
306 for candidate in (
307 *detect.extract_meta_contents(bounded, "property", "og:title"),
308 *detect.extract_title_texts(bounded),
309 ):
310 cleaned = _clean_page_title(candidate, site_name)
311 if cleaned:
312 return cleaned
313 return ""
314
315
316 def read_roster(
317 hosts: list[str],
318 *,
319 company: str,
320 deadline: float,
321 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
322 """Rows from the first of ``hosts`` with a job sitemap, and what was read.
323
324 Rows with no title (a site that walls its role pages too) are not
325 returned; ``board_total`` still counts every job URL, and
326 ``board_titles_missing`` says the titles could not be read.
327 """
328 host, urls, partial = job_urls(hosts, deadline=deadline)
329 info: dict[str, Any] = {
330 "board_total": len(urls), "board_sitemap_host": host, "board_total_floor": partial,
331 }
332 if not urls:
333 return [], info
334 titled = [(url, title_from_url(url)) for url, _lastmod in urls]
335 if sum(1 for _url, title in titled if title) < len(titled) / 2:
336 titled = _titles_from_pages([url for url, _lastmod in urls[:TITLE_PAGE_LIMIT]], company, deadline)
337 info["board_titles_from_pages"] = True
338 if not titled:
339 info["board_titles_missing"] = True
340 return [], info
341 items = []
342 for url, title in titled:
343 if not title:
344 continue
345 item = jobs._ats_item(
346 provider=PROVIDER_SITEMAP,
347 slug=host,
348 ident=url.rstrip("/").rsplit("/", 1)[-1][:60],
349 title=title,
350 url=url,
351 description="",
352 date=None,
353 department="",
354 location="",
355 company_name=company,
356 whole_posting=True,
357 )
358 items.append(item)
359 info["board_rows_read"] = len(items)
360 info["board_cut_short"] = len(items) < len(urls)
361 return items, info
362
363
364 def _titles_from_pages(urls: list[str], company: str, deadline: float) -> list[tuple[str, str]]:
365 def call(url: str) -> Callable[[float], Any]:
366 return lambda http_deadline: _on_site(url, lambda landed: jobs.role_page_text(
367 url, timeout=TIMEOUT_SECONDS, deadline_monotonic=http_deadline, landed=landed,
368 redirect_guard=_guard(url), max_bytes=MAX_PAGE_BYTES,
369 ))
370
371 # The first wave tells whether the role pages can be read at all: a site
372 # that walls them answers every one of those with a block, and the rest
373 # are not asked.
374 wave = TITLE_FIRST_WAVE
375 titled: list[tuple[str, str]] = []
376 with http.capture_failures():
377 first_pages = jobs._workday_run([call(url) for url in urls[:wave]], deadline, jobs._clock())
378 for url, page in zip(urls[:wave], first_pages):
379 if isinstance(page, str):
380 title = title_from_page(page, company)
381 if title:
382 titled.append((url, title))
383 if titled and len(urls) > wave:
384 rest_pages = jobs._workday_run([call(url) for url in urls[wave:]], deadline, jobs._clock())
385 for url, page in zip(urls[wave:], rest_pages):
386 if isinstance(page, str):
387 title = title_from_page(page, company)
388 if title:
389 titled.append((url, title))
390 return titled
391
391 lines PYTHON