scrapeplanner 0.1.0__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.
- scrapeplanner/__init__.py +5 -0
- scrapeplanner/__main__.py +5 -0
- scrapeplanner/analyze.py +389 -0
- scrapeplanner/cli.py +108 -0
- scrapeplanner/config.py +25 -0
- scrapeplanner/detectors/__init__.py +0 -0
- scrapeplanner/detectors/antibot.py +259 -0
- scrapeplanner/detectors/embedded.py +142 -0
- scrapeplanner/detectors/feeds.py +259 -0
- scrapeplanner/detectors/platform.py +349 -0
- scrapeplanner/detectors/rendering.py +65 -0
- scrapeplanner/detectors/robots.py +40 -0
- scrapeplanner/detectors/sitemaps.py +119 -0
- scrapeplanner/detectors/structured.py +321 -0
- scrapeplanner/fetch.py +378 -0
- scrapeplanner/html.py +131 -0
- scrapeplanner/models.py +370 -0
- scrapeplanner/output/__init__.py +0 -0
- scrapeplanner/output/json_out.py +9 -0
- scrapeplanner/output/profile.py +80 -0
- scrapeplanner/output/terminal.py +293 -0
- scrapeplanner/planner.py +465 -0
- scrapeplanner/py.typed +0 -0
- scrapeplanner/record.py +135 -0
- scrapeplanner-0.1.0.dist-info/METADATA +452 -0
- scrapeplanner-0.1.0.dist-info/RECORD +29 -0
- scrapeplanner-0.1.0.dist-info/WHEEL +4 -0
- scrapeplanner-0.1.0.dist-info/entry_points.txt +2 -0
- scrapeplanner-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Name the anti-bot vendor in front of a site, and recognise block pages.
|
|
2
|
+
|
|
3
|
+
Detection only. The signals below are public, documented artefacts (header
|
|
4
|
+
names, cookie names, script hosts, the titles of block pages). This module
|
|
5
|
+
never tries to avoid them, and nothing in this project does (D-007).
|
|
6
|
+
|
|
7
|
+
Two levels per vendor:
|
|
8
|
+
|
|
9
|
+
* ``present``: a header, cookie or script shows the vendor in front of the
|
|
10
|
+
site, but the page was served;
|
|
11
|
+
* ``challenge``: the response is a block or interstitial page from the vendor.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Literal
|
|
20
|
+
|
|
21
|
+
from scrapeplanner.models import AntiBotReport, VendorHit, VendorName
|
|
22
|
+
|
|
23
|
+
Kind = Literal["header", "header_value", "challenge_header", "cookie", "marker", "challenge"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Signal:
|
|
28
|
+
vendor: VendorName
|
|
29
|
+
kind: Kind
|
|
30
|
+
pattern: str
|
|
31
|
+
"""header: header name; header_value / challenge_header: ``name=regex`` on the
|
|
32
|
+
header value; cookie: regex on cookie names; marker / challenge: regex
|
|
33
|
+
searched in the body (a challenge marker counts only on an interstitial)."""
|
|
34
|
+
label: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
SIGNALS: tuple[Signal, ...] = (
|
|
38
|
+
# Cloudflare. As a CDN it is everywhere; that alone is "present".
|
|
39
|
+
Signal("cloudflare", "header", "cf-ray", "header cf-ray"),
|
|
40
|
+
Signal("cloudflare", "header_value", r"server=^cloudflare", "header server: cloudflare"),
|
|
41
|
+
Signal("cloudflare", "cookie", r"^__cf_bm$", "cookie __cf_bm (bot management)"),
|
|
42
|
+
Signal("cloudflare", "cookie", r"^cf_clearance$", "cookie cf_clearance"),
|
|
43
|
+
Signal(
|
|
44
|
+
"cloudflare",
|
|
45
|
+
"challenge_header",
|
|
46
|
+
r"cf-mitigated=challenge",
|
|
47
|
+
"header cf-mitigated: challenge",
|
|
48
|
+
),
|
|
49
|
+
Signal(
|
|
50
|
+
"cloudflare",
|
|
51
|
+
"challenge",
|
|
52
|
+
r"<title>\s*Just a moment\.\.\.\s*</title>",
|
|
53
|
+
"'Just a moment...' interstitial",
|
|
54
|
+
),
|
|
55
|
+
Signal("cloudflare", "challenge", r"window\._cf_chl_opt", "challenge script _cf_chl_opt"),
|
|
56
|
+
Signal(
|
|
57
|
+
"cloudflare",
|
|
58
|
+
"challenge",
|
|
59
|
+
r"Attention Required! \| Cloudflare",
|
|
60
|
+
"'Attention Required' block page",
|
|
61
|
+
),
|
|
62
|
+
Signal(
|
|
63
|
+
"cloudflare", "challenge", r"Sorry, you have been blocked", "'you have been blocked' page"
|
|
64
|
+
),
|
|
65
|
+
# Akamai
|
|
66
|
+
Signal("akamai", "header_value", r"server=^AkamaiGHost", "header server: AkamaiGHost"),
|
|
67
|
+
Signal("akamai", "header", "akamai-grn", "header akamai-grn"),
|
|
68
|
+
Signal("akamai", "header", "x-akamai-transformed", "header x-akamai-transformed"),
|
|
69
|
+
Signal("akamai", "cookie", r"^_abck$", "cookie _abck (Bot Manager)"),
|
|
70
|
+
Signal("akamai", "cookie", r"^bm_sz$", "cookie bm_sz (Bot Manager)"),
|
|
71
|
+
Signal("akamai", "cookie", r"^ak_bmsc$", "cookie ak_bmsc (Bot Manager)"),
|
|
72
|
+
Signal("akamai", "cookie", r"^bm_sv$", "cookie bm_sv (Bot Manager)"),
|
|
73
|
+
Signal("akamai", "challenge", r"errors\.edgesuite\.net", "Akamai 'Access Denied' reference"),
|
|
74
|
+
Signal(
|
|
75
|
+
"akamai",
|
|
76
|
+
"challenge",
|
|
77
|
+
r"sec-if-cpt-container|/_sec/cp_challenge/",
|
|
78
|
+
"Akamai sec-cpt challenge",
|
|
79
|
+
),
|
|
80
|
+
# DataDome
|
|
81
|
+
Signal("datadome", "header", "x-datadome", "header x-datadome"),
|
|
82
|
+
Signal("datadome", "header", "x-datadome-cid", "header x-datadome-cid"),
|
|
83
|
+
Signal("datadome", "header", "x-dd-b", "header x-dd-b"),
|
|
84
|
+
Signal("datadome", "cookie", r"^datadome$", "cookie datadome"),
|
|
85
|
+
Signal("datadome", "marker", r"js\.datadome\.co|datadome\.co/tags\.js", "DataDome tag script"),
|
|
86
|
+
Signal("datadome", "challenge", r"captcha-delivery\.com", "DataDome captcha-delivery page"),
|
|
87
|
+
# HUMAN (PerimeterX)
|
|
88
|
+
Signal("human", "cookie", r"^_px(3|2|hd|vid|de)$", "cookie _px* (HUMAN)"),
|
|
89
|
+
Signal("human", "cookie", r"^pxcts$", "cookie pxcts (HUMAN)"),
|
|
90
|
+
Signal(
|
|
91
|
+
"human",
|
|
92
|
+
"marker",
|
|
93
|
+
r"client\.perimeterx\.net|client\.px-cloud\.net|px-cdn\.net",
|
|
94
|
+
"HUMAN sensor script",
|
|
95
|
+
),
|
|
96
|
+
Signal("human", "marker", r"window\._pxAppId", "HUMAN _pxAppId"),
|
|
97
|
+
Signal("human", "challenge", r"px-captcha|captcha\.px-cdn\.net", "HUMAN px-captcha block page"),
|
|
98
|
+
# Imperva (Incapsula)
|
|
99
|
+
Signal("imperva", "header", "x-iinfo", "header x-iinfo"),
|
|
100
|
+
Signal("imperva", "header_value", r"x-cdn=(?i:imperva|incapsula)", "header x-cdn: Imperva"),
|
|
101
|
+
Signal(
|
|
102
|
+
"imperva", "cookie", r"^(visid_incap_|incap_ses_|nlbi_)", "cookie visid_incap_/incap_ses_"
|
|
103
|
+
),
|
|
104
|
+
Signal("imperva", "cookie", r"^reese84$", "cookie reese84 (Imperva ABP)"),
|
|
105
|
+
Signal(
|
|
106
|
+
"imperva", "challenge", r"_Incapsula_Resource|Incapsula incident ID", "Incapsula block page"
|
|
107
|
+
),
|
|
108
|
+
# Kasada
|
|
109
|
+
Signal("kasada", "header", "x-kpsdk-ct", "header x-kpsdk-ct"),
|
|
110
|
+
Signal("kasada", "header", "x-kpsdk-cd", "header x-kpsdk-cd"),
|
|
111
|
+
Signal("kasada", "header", "x-kpsdk-r", "header x-kpsdk-r"),
|
|
112
|
+
Signal("kasada", "marker", r"\bKPSDK\b", "Kasada KPSDK script"),
|
|
113
|
+
Signal("kasada", "challenge", r"\bKPSDK\b", "Kasada interstitial"),
|
|
114
|
+
# AWS WAF (Bot Control). Not one of the big six, but common enough to name.
|
|
115
|
+
Signal("aws_waf", "cookie", r"^aws-waf-token$", "cookie aws-waf-token"),
|
|
116
|
+
Signal(
|
|
117
|
+
"aws_waf",
|
|
118
|
+
"challenge_header",
|
|
119
|
+
r"x-amzn-waf-action=challenge|captcha",
|
|
120
|
+
"header x-amzn-waf-action",
|
|
121
|
+
),
|
|
122
|
+
Signal(
|
|
123
|
+
"aws_waf",
|
|
124
|
+
"challenge",
|
|
125
|
+
r"awsWafCookieDomainList|AwsWafIntegration",
|
|
126
|
+
"AWS WAF challenge page",
|
|
127
|
+
),
|
|
128
|
+
# A site's own bot check (no vendor named): CAPTCHA forms and "are you a robot" pages.
|
|
129
|
+
# Like every challenge marker these count only on a small or 4xx/5xx page.
|
|
130
|
+
Signal("own_check", "challenge", r"/errors(?:_page)?/validateCaptcha", "validateCaptcha form"),
|
|
131
|
+
Signal("own_check", "challenge", r"""<form[^>]+action=["'][^"']*captcha""", "CAPTCHA form"),
|
|
132
|
+
Signal(
|
|
133
|
+
"own_check",
|
|
134
|
+
"challenge",
|
|
135
|
+
r"g-recaptcha|class=[\"']h-captcha|cf-turnstile|challenges\.cloudflare\.com/turnstile",
|
|
136
|
+
"CAPTCHA widget",
|
|
137
|
+
),
|
|
138
|
+
Signal(
|
|
139
|
+
"own_check",
|
|
140
|
+
"challenge",
|
|
141
|
+
r"verify (?:that )?you(?:'re| are) (?:a )?human|are you a robot|robot check|"
|
|
142
|
+
r"unusual traffic from your (?:computer )?network|"
|
|
143
|
+
r"click the button below to continue shopping",
|
|
144
|
+
"'are you a robot' page",
|
|
145
|
+
),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
CDN_ONLY_EVIDENCE = frozenset(
|
|
149
|
+
{
|
|
150
|
+
"header cf-ray",
|
|
151
|
+
"header server: cloudflare",
|
|
152
|
+
"header server: AkamaiGHost",
|
|
153
|
+
"header akamai-grn",
|
|
154
|
+
"header x-akamai-transformed",
|
|
155
|
+
}
|
|
156
|
+
)
|
|
157
|
+
"""Signals that show a CDN in front of the site, not its bot management."""
|
|
158
|
+
INTERSTITIAL_MAX_CHARS = 30_000
|
|
159
|
+
"""Challenge markers in a large 2xx page are an embedded script, not a block."""
|
|
160
|
+
BLOCK_STATUSES = frozenset({401, 403, 429, 503})
|
|
161
|
+
|
|
162
|
+
_COMPILED: dict[str, re.Pattern[str]] = {}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _regex(pattern: str) -> re.Pattern[str]:
|
|
166
|
+
compiled = _COMPILED.get(pattern)
|
|
167
|
+
if compiled is None:
|
|
168
|
+
compiled = re.compile(pattern, re.IGNORECASE)
|
|
169
|
+
_COMPILED[pattern] = compiled
|
|
170
|
+
return compiled
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def detect(
|
|
174
|
+
status: int,
|
|
175
|
+
headers: Mapping[str, str],
|
|
176
|
+
cookie_names: Sequence[str],
|
|
177
|
+
text: str,
|
|
178
|
+
) -> list[VendorHit]:
|
|
179
|
+
"""Vendors seen in one response."""
|
|
180
|
+
lowered = {key.lower(): value for key, value in headers.items()}
|
|
181
|
+
interstitial = status >= 400 or len(text) <= INTERSTITIAL_MAX_CHARS
|
|
182
|
+
hits: dict[str, VendorHit] = {}
|
|
183
|
+
for signal in SIGNALS:
|
|
184
|
+
if signal.vendor == "own_check" and not interstitial:
|
|
185
|
+
continue # a CAPTCHA widget in a normal page (e.g. a newsletter form) is no block
|
|
186
|
+
fired = False
|
|
187
|
+
challenge = False
|
|
188
|
+
if signal.kind == "header":
|
|
189
|
+
fired = signal.pattern in lowered
|
|
190
|
+
elif signal.kind in ("header_value", "challenge_header"):
|
|
191
|
+
name, _, value_pattern = signal.pattern.partition("=")
|
|
192
|
+
value = lowered.get(name)
|
|
193
|
+
fired = value is not None and bool(_regex(value_pattern).search(value))
|
|
194
|
+
challenge = fired and signal.kind == "challenge_header"
|
|
195
|
+
elif signal.kind == "cookie":
|
|
196
|
+
fired = any(_regex(signal.pattern).search(name) for name in cookie_names)
|
|
197
|
+
elif signal.kind == "marker":
|
|
198
|
+
fired = bool(_regex(signal.pattern).search(text))
|
|
199
|
+
else: # challenge marker
|
|
200
|
+
fired = bool(_regex(signal.pattern).search(text))
|
|
201
|
+
challenge = fired and interstitial
|
|
202
|
+
if not fired:
|
|
203
|
+
continue
|
|
204
|
+
hit = hits.setdefault(signal.vendor, VendorHit(vendor=signal.vendor, status="present"))
|
|
205
|
+
if signal.label not in hit.evidence:
|
|
206
|
+
hit.evidence.append(signal.label)
|
|
207
|
+
if challenge:
|
|
208
|
+
hit.status = "challenge"
|
|
209
|
+
if status == 429 and "kasada" in hits:
|
|
210
|
+
hits["kasada"].status = "challenge"
|
|
211
|
+
for hit in hits.values():
|
|
212
|
+
hit.bot_management = _managed(hit)
|
|
213
|
+
return list(hits.values())
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _managed(hit: VendorHit) -> bool:
|
|
217
|
+
if hit.status == "challenge":
|
|
218
|
+
return True
|
|
219
|
+
return not set(hit.evidence) <= CDN_ONLY_EVIDENCE
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def classify_block(
|
|
223
|
+
status: int, headers: Mapping[str, str], cookie_names: Sequence[str], text: str
|
|
224
|
+
) -> tuple[Literal["blocked", "challenge", "rate_limited"], str] | None:
|
|
225
|
+
"""Should the run stop after this response? Returns (reason, detail) or None."""
|
|
226
|
+
hits = detect(status, headers, cookie_names, text)
|
|
227
|
+
for hit in hits:
|
|
228
|
+
if hit.status == "challenge":
|
|
229
|
+
return "challenge", f"{hit.vendor} challenge page (HTTP {status}: {hit.evidence[-1]})"
|
|
230
|
+
if status == 429:
|
|
231
|
+
return "rate_limited", "HTTP 429 Too Many Requests"
|
|
232
|
+
if status in BLOCK_STATUSES:
|
|
233
|
+
vendors = ", ".join(hit.vendor for hit in hits)
|
|
234
|
+
suffix = f"; {vendors} in front of the site" if vendors else ""
|
|
235
|
+
return "blocked", f"HTTP {status}{suffix}"
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def merge(responses: Iterable[tuple[str, list[VendorHit]]]) -> AntiBotReport:
|
|
240
|
+
"""Combine per-response hits (``(url, hits)``) into one report."""
|
|
241
|
+
report = AntiBotReport()
|
|
242
|
+
by_vendor: dict[str, VendorHit] = {}
|
|
243
|
+
for url, hits in responses:
|
|
244
|
+
for hit in hits:
|
|
245
|
+
merged = by_vendor.get(hit.vendor)
|
|
246
|
+
if merged is None:
|
|
247
|
+
merged = VendorHit(vendor=hit.vendor, status="present")
|
|
248
|
+
by_vendor[hit.vendor] = merged
|
|
249
|
+
report.vendors.append(merged)
|
|
250
|
+
for item in hit.evidence:
|
|
251
|
+
if item not in merged.evidence:
|
|
252
|
+
merged.evidence.append(item)
|
|
253
|
+
if hit.status == "challenge":
|
|
254
|
+
merged.status = "challenge"
|
|
255
|
+
if not report.challenged:
|
|
256
|
+
report.challenged = True
|
|
257
|
+
report.challenge_url = url
|
|
258
|
+
merged.bot_management = _managed(merged)
|
|
259
|
+
return report
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Embedded state: data that frameworks serialise into the page for hydration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from scrapeplanner.html import HtmlDoc, Script
|
|
10
|
+
from scrapeplanner.models import EmbeddedBlob, EmbeddedStateReport
|
|
11
|
+
|
|
12
|
+
MIN_JSON_SCRIPT_BYTES = 1_000
|
|
13
|
+
"""Smaller application/json scripts are usually config, not data."""
|
|
14
|
+
MAX_KEYS = 15
|
|
15
|
+
MAX_BLOBS = 10
|
|
16
|
+
|
|
17
|
+
_WINDOW_STATE = re.compile(
|
|
18
|
+
r"window\.(__APOLLO_STATE__|__INITIAL_STATE__|__PRELOADED_STATE__|__REDUX_STATE__|"
|
|
19
|
+
r"__INITIAL_DATA__|__STATE__|__DATA__|__APP_STATE__|__SERVER_DATA__)\s*=\s*"
|
|
20
|
+
)
|
|
21
|
+
_NUXT2 = re.compile(r"window\.__NUXT__\s*=")
|
|
22
|
+
_NEXT_FLIGHT = "self.__next_f.push("
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _keys(value: Any) -> list[str]:
|
|
26
|
+
if isinstance(value, dict):
|
|
27
|
+
return [str(key) for key in list(value)[:MAX_KEYS]]
|
|
28
|
+
return []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _json_after(text: str, start: int) -> Any:
|
|
32
|
+
"""Parse the JSON value that starts at ``text[start:]`` (raw_decode stops at its end)."""
|
|
33
|
+
try:
|
|
34
|
+
value, _ = json.JSONDecoder().raw_decode(text[start:].lstrip())
|
|
35
|
+
except (json.JSONDecodeError, RecursionError):
|
|
36
|
+
return None
|
|
37
|
+
return value
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _apollo_keys(state: Any) -> list[str]:
|
|
41
|
+
"""Apollo normalised cache: summarise by typename ('Product:123' -> 'Product')."""
|
|
42
|
+
if not isinstance(state, dict):
|
|
43
|
+
return []
|
|
44
|
+
counts: dict[str, int] = {}
|
|
45
|
+
for key in state:
|
|
46
|
+
name = str(key).split(":", 1)[0]
|
|
47
|
+
counts[name] = counts.get(name, 0) + 1
|
|
48
|
+
ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
|
|
49
|
+
return [f"{name} x{count}" for name, count in ranked[:MAX_KEYS]]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _locator(script: Script) -> str:
|
|
53
|
+
if script.id:
|
|
54
|
+
return f"script#{script.id}"
|
|
55
|
+
for attr in sorted(script.attrs):
|
|
56
|
+
if attr.startswith("data-"):
|
|
57
|
+
return f"script[{attr}]"
|
|
58
|
+
return f"script[type={script.type}]"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def detect(doc: HtmlDoc) -> EmbeddedStateReport:
|
|
62
|
+
blobs: list[EmbeddedBlob] = []
|
|
63
|
+
flight_chunks = 0
|
|
64
|
+
flight_bytes = 0
|
|
65
|
+
for script in doc.scripts:
|
|
66
|
+
text = script.text
|
|
67
|
+
size = len(text.encode("utf-8"))
|
|
68
|
+
if script.id == "__NEXT_DATA__":
|
|
69
|
+
data = _json_after(text, 0)
|
|
70
|
+
details = {}
|
|
71
|
+
if isinstance(data, dict):
|
|
72
|
+
for key in ("page", "buildId"):
|
|
73
|
+
if isinstance(data.get(key), str):
|
|
74
|
+
details[key] = data[key]
|
|
75
|
+
props = data.get("props")
|
|
76
|
+
page_props = props.get("pageProps") if isinstance(props, dict) else None
|
|
77
|
+
else:
|
|
78
|
+
page_props = None
|
|
79
|
+
blobs.append(
|
|
80
|
+
EmbeddedBlob(
|
|
81
|
+
kind="next_data",
|
|
82
|
+
locator="script#__NEXT_DATA__",
|
|
83
|
+
bytes=size,
|
|
84
|
+
keys=_keys(page_props),
|
|
85
|
+
details=details,
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
elif script.id == "__NUXT_DATA__":
|
|
89
|
+
blobs.append(
|
|
90
|
+
EmbeddedBlob(
|
|
91
|
+
kind="nuxt_data",
|
|
92
|
+
locator="script#__NUXT_DATA__",
|
|
93
|
+
bytes=size,
|
|
94
|
+
details={"format": "devalue (Nuxt 3)"},
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
elif _NEXT_FLIGHT in text:
|
|
98
|
+
flight_chunks += text.count(_NEXT_FLIGHT)
|
|
99
|
+
flight_bytes += size
|
|
100
|
+
elif _NUXT2.search(text):
|
|
101
|
+
match = _NUXT2.search(text)
|
|
102
|
+
value = _json_after(text, match.end()) if match else None
|
|
103
|
+
blobs.append(
|
|
104
|
+
EmbeddedBlob(
|
|
105
|
+
kind="nuxt_state",
|
|
106
|
+
locator="window.__NUXT__",
|
|
107
|
+
bytes=size,
|
|
108
|
+
keys=_keys(value),
|
|
109
|
+
details={"format": "json" if value is not None else "javascript (Nuxt 2)"},
|
|
110
|
+
)
|
|
111
|
+
)
|
|
112
|
+
elif match := _WINDOW_STATE.search(text):
|
|
113
|
+
name = match.group(1)
|
|
114
|
+
value = _json_after(text, match.end())
|
|
115
|
+
apollo = name == "__APOLLO_STATE__"
|
|
116
|
+
blobs.append(
|
|
117
|
+
EmbeddedBlob(
|
|
118
|
+
kind="apollo_state" if apollo else "redux_state",
|
|
119
|
+
locator=f"window.{name}",
|
|
120
|
+
bytes=size,
|
|
121
|
+
keys=_apollo_keys(value) if apollo else _keys(value),
|
|
122
|
+
details={"format": "json" if value is not None else "javascript"},
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
elif script.type in ("application/json", "text/json") and size >= MIN_JSON_SCRIPT_BYTES:
|
|
126
|
+
value = _json_after(text, 0)
|
|
127
|
+
blobs.append(
|
|
128
|
+
EmbeddedBlob(
|
|
129
|
+
kind="json_script", locator=_locator(script), bytes=size, keys=_keys(value)
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
if flight_chunks:
|
|
133
|
+
blobs.append(
|
|
134
|
+
EmbeddedBlob(
|
|
135
|
+
kind="next_flight",
|
|
136
|
+
locator="self.__next_f.push",
|
|
137
|
+
bytes=flight_bytes,
|
|
138
|
+
details={"chunks": str(flight_chunks), "format": "React Server Components"},
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
blobs.sort(key=lambda blob: -blob.bytes)
|
|
142
|
+
return EmbeddedStateReport(blobs=blobs[:MAX_BLOBS])
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Public feeds and JSON endpoints: which to probe, and whether a response is valid.
|
|
2
|
+
|
|
3
|
+
``candidates()`` proposes URLs; the analyzer decides how many to request
|
|
4
|
+
within the budget; ``evaluate()`` checks a response's shape.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from scrapeplanner.html import HtmlDoc
|
|
15
|
+
from scrapeplanner.models import FeedCandidate, PlatformReport
|
|
16
|
+
|
|
17
|
+
SHOPIFY_PAGE_SIZE = 250
|
|
18
|
+
WOO_PAGE_SIZE = 100
|
|
19
|
+
WP_PAGE_SIZE = 100
|
|
20
|
+
CKAN_PAGE_SIZE = 1000
|
|
21
|
+
LEVER_PAGE_SIZE = 100
|
|
22
|
+
MAX_FIELDS = 15
|
|
23
|
+
|
|
24
|
+
_FEED_TYPES = {
|
|
25
|
+
"application/rss+xml": "rss",
|
|
26
|
+
"application/atom+xml": "atom",
|
|
27
|
+
"application/feed+json": "json_feed",
|
|
28
|
+
"application/json": "json_link",
|
|
29
|
+
}
|
|
30
|
+
_SHOPIFY_HANDLE = re.compile(r"/products/([a-z0-9][a-z0-9\-_.%]*)", re.IGNORECASE)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _origin(url: str) -> str:
|
|
34
|
+
parts = urlsplit(url)
|
|
35
|
+
return f"{parts.scheme}://{parts.netloc}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def shopify_handle(doc: HtmlDoc) -> str | None:
|
|
39
|
+
for path in doc.same_site_paths():
|
|
40
|
+
match = _SHOPIFY_HANDLE.search(path)
|
|
41
|
+
if match and not match.group(1).endswith((".js", ".json")):
|
|
42
|
+
return match.group(1)
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_BOARD_PATH = re.compile(r"^/(?:embed/job_board\?for=)?([A-Za-z0-9][A-Za-z0-9._-]*)")
|
|
47
|
+
_EMBED_TOKEN = {
|
|
48
|
+
"greenhouse": re.compile(
|
|
49
|
+
r"boards\.greenhouse\.io/embed/job_board(?:/js)?\?for=([A-Za-z0-9._-]+)"
|
|
50
|
+
),
|
|
51
|
+
"lever": re.compile(r"jobs\.(?:eu\.)?lever\.co/([A-Za-z0-9._-]+)"),
|
|
52
|
+
"ashby": re.compile(r"jobs\.ashbyhq\.com/([A-Za-z0-9._%-]+)"),
|
|
53
|
+
}
|
|
54
|
+
BOARD_APIS = {
|
|
55
|
+
"greenhouse": ("greenhouse_api", "https://boards-api.greenhouse.io/v1/boards/{token}/jobs"),
|
|
56
|
+
"lever": ("lever_api", "https://api.lever.co/v0/postings/{token}?mode=json&limit=100"),
|
|
57
|
+
"ashby": ("ashby_api", "https://api.ashbyhq.com/posting-api/job-board/{token}"),
|
|
58
|
+
}
|
|
59
|
+
"""The documented public job-board APIs of each hosted board."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def job_board_token(name: str, page_url: str, doc: HtmlDoc | None) -> tuple[str, str] | None:
|
|
63
|
+
"""(feed kind, API URL) for a Greenhouse, Lever or Ashby board, from its URL or embed."""
|
|
64
|
+
if name not in BOARD_APIS:
|
|
65
|
+
return None
|
|
66
|
+
parts = urlsplit(page_url)
|
|
67
|
+
token = None
|
|
68
|
+
hosted = ("greenhouse.io", "lever.co", "ashbyhq.com")
|
|
69
|
+
if parts.netloc.endswith(hosted):
|
|
70
|
+
match = _BOARD_PATH.match(parts.path)
|
|
71
|
+
token = match.group(1) if match else None
|
|
72
|
+
if token is None and doc is not None:
|
|
73
|
+
match = _EMBED_TOKEN[name].search(doc.html)
|
|
74
|
+
token = match.group(1) if match else None
|
|
75
|
+
if not token:
|
|
76
|
+
return None
|
|
77
|
+
kind, template = BOARD_APIS[name]
|
|
78
|
+
return kind, template.format(token=token)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def candidates(platform: PlatformReport, doc: HtmlDoc | None, page_url: str) -> list[FeedCandidate]:
|
|
82
|
+
"""Feeds worth probing, best first. All start as ``linked`` (not requested)."""
|
|
83
|
+
origin = _origin(page_url)
|
|
84
|
+
found: list[FeedCandidate] = []
|
|
85
|
+
|
|
86
|
+
def add(kind: str, url: str, note: str | None = None) -> None:
|
|
87
|
+
if all(existing.url != url for existing in found):
|
|
88
|
+
found.append(FeedCandidate(kind=kind, url=url, status="linked", note=note)) # type: ignore[arg-type]
|
|
89
|
+
|
|
90
|
+
is_wordpress = platform.name in ("woocommerce", "wordpress") or (
|
|
91
|
+
"wordpress" in platform.frameworks
|
|
92
|
+
)
|
|
93
|
+
if platform.name == "shopify":
|
|
94
|
+
add("shopify_products_json", f"{origin}/products.json?limit={SHOPIFY_PAGE_SIZE}")
|
|
95
|
+
handle = shopify_handle(doc) if doc else None
|
|
96
|
+
if handle:
|
|
97
|
+
add("shopify_product_js", f"{origin}/products/{handle}.js")
|
|
98
|
+
if platform.name == "woocommerce":
|
|
99
|
+
add("woo_store_api", f"{origin}/wp-json/wc/store/v1/products?per_page=1")
|
|
100
|
+
board = job_board_token(platform.name, page_url, doc)
|
|
101
|
+
if board is not None:
|
|
102
|
+
add(*board)
|
|
103
|
+
if platform.name == "ckan":
|
|
104
|
+
add("ckan_api", f"{origin}/api/3/action/package_search?rows=1")
|
|
105
|
+
if doc is not None:
|
|
106
|
+
for link in doc.links:
|
|
107
|
+
if "alternate" not in link.rel.split():
|
|
108
|
+
continue
|
|
109
|
+
kind = _FEED_TYPES.get(link.type)
|
|
110
|
+
if kind and _origin(link.href) == origin:
|
|
111
|
+
# WordPress links each page's own JSON (/wp-json/wp/v2/pages/<id>) and
|
|
112
|
+
# oEmbed data as "alternate"; neither is a feed of records.
|
|
113
|
+
if any(part in link.href for part in ("/comments/feed", "oembed", "/wp-json/")):
|
|
114
|
+
continue
|
|
115
|
+
add(kind, link.href, note=link.title or None)
|
|
116
|
+
if is_wordpress and platform.name != "woocommerce":
|
|
117
|
+
add("wp_rest", f"{origin}/wp-json/wp/v2/posts?per_page=1")
|
|
118
|
+
return found
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _fields(item: Any) -> list[str]:
|
|
122
|
+
if isinstance(item, dict):
|
|
123
|
+
return [str(key) for key in list(item)[:MAX_FIELDS]]
|
|
124
|
+
return []
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _xml_count(text: str, tag: str) -> int:
|
|
128
|
+
return len(re.findall(rf"<{tag}[\s>]", text))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def evaluate(
|
|
132
|
+
candidate: FeedCandidate,
|
|
133
|
+
status: int,
|
|
134
|
+
content_type: str,
|
|
135
|
+
text: str,
|
|
136
|
+
headers: dict[str, str],
|
|
137
|
+
) -> FeedCandidate:
|
|
138
|
+
"""Fill status, items and fields from a probe response."""
|
|
139
|
+
result = candidate.model_copy()
|
|
140
|
+
result.http_status = status
|
|
141
|
+
if status in (404, 410):
|
|
142
|
+
result.status = "not_found"
|
|
143
|
+
return result
|
|
144
|
+
if not 200 <= status < 300:
|
|
145
|
+
result.status = "invalid"
|
|
146
|
+
result.note = f"HTTP {status}"
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
kind = candidate.kind
|
|
150
|
+
if kind in ("rss", "atom"):
|
|
151
|
+
tag = "item" if kind == "rss" else "entry"
|
|
152
|
+
count = _xml_count(text, tag)
|
|
153
|
+
if count or "<rss" in text[:500] or "<feed" in text[:500]:
|
|
154
|
+
result.status = "ok"
|
|
155
|
+
result.items_seen = count
|
|
156
|
+
result.page_size = count or None
|
|
157
|
+
else:
|
|
158
|
+
result.status = "invalid"
|
|
159
|
+
result.note = "not an RSS/Atom document"
|
|
160
|
+
return result
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
data = json.loads(text)
|
|
164
|
+
except (json.JSONDecodeError, RecursionError):
|
|
165
|
+
result.status = "invalid"
|
|
166
|
+
result.note = f"not JSON ({content_type or 'no content-type'})"
|
|
167
|
+
return result
|
|
168
|
+
|
|
169
|
+
lowered = {key.lower(): value for key, value in headers.items()}
|
|
170
|
+
if kind in ("greenhouse_api", "ashby_api"):
|
|
171
|
+
jobs = data.get("jobs") if isinstance(data, dict) else None
|
|
172
|
+
if isinstance(jobs, list):
|
|
173
|
+
result.status = "ok"
|
|
174
|
+
result.items_seen = len(jobs)
|
|
175
|
+
result.total_items = len(jobs)
|
|
176
|
+
result.fields = _fields(jobs[0]) if jobs else []
|
|
177
|
+
result.note = "every open job in one response"
|
|
178
|
+
else:
|
|
179
|
+
result.status = "invalid"
|
|
180
|
+
result.note = "no 'jobs' list"
|
|
181
|
+
return result
|
|
182
|
+
if kind == "lever_api":
|
|
183
|
+
if isinstance(data, list):
|
|
184
|
+
result.status = "ok"
|
|
185
|
+
result.items_seen = len(data)
|
|
186
|
+
result.page_size = LEVER_PAGE_SIZE
|
|
187
|
+
result.fields = _fields(data[0]) if data else []
|
|
188
|
+
if len(data) < LEVER_PAGE_SIZE:
|
|
189
|
+
result.total_items = len(data)
|
|
190
|
+
result.note = "every open posting in one response"
|
|
191
|
+
else:
|
|
192
|
+
result.note = f"{LEVER_PAGE_SIZE} per page; more with &skip="
|
|
193
|
+
else:
|
|
194
|
+
result.status = "invalid"
|
|
195
|
+
result.note = "expected a JSON list"
|
|
196
|
+
return result
|
|
197
|
+
if kind == "ckan_api":
|
|
198
|
+
found = data.get("result") if isinstance(data, dict) else None
|
|
199
|
+
if isinstance(found, dict) and isinstance(found.get("count"), int):
|
|
200
|
+
result.status = "ok"
|
|
201
|
+
rows = found.get("results")
|
|
202
|
+
result.items_seen = len(rows) if isinstance(rows, list) else 0
|
|
203
|
+
result.total_items = found["count"]
|
|
204
|
+
result.page_size = CKAN_PAGE_SIZE
|
|
205
|
+
result.fields = _fields(rows[0]) if isinstance(rows, list) and rows else []
|
|
206
|
+
else:
|
|
207
|
+
result.status = "invalid"
|
|
208
|
+
result.note = "no CKAN package_search result"
|
|
209
|
+
return result
|
|
210
|
+
if kind == "shopify_products_json":
|
|
211
|
+
products = data.get("products") if isinstance(data, dict) else None
|
|
212
|
+
if isinstance(products, list):
|
|
213
|
+
result.status = "ok"
|
|
214
|
+
result.items_seen = len(products)
|
|
215
|
+
result.page_size = SHOPIFY_PAGE_SIZE
|
|
216
|
+
result.fields = _fields(products[0]) if products else []
|
|
217
|
+
if len(products) < SHOPIFY_PAGE_SIZE:
|
|
218
|
+
result.note = f"whole catalog fits in one page ({len(products)} products)"
|
|
219
|
+
else:
|
|
220
|
+
result.status = "invalid"
|
|
221
|
+
result.note = "no 'products' list"
|
|
222
|
+
elif kind == "shopify_product_js":
|
|
223
|
+
if isinstance(data, dict) and "variants" in data:
|
|
224
|
+
result.status = "ok"
|
|
225
|
+
result.items_seen = 1
|
|
226
|
+
result.fields = _fields(data)
|
|
227
|
+
else:
|
|
228
|
+
result.status = "invalid"
|
|
229
|
+
result.note = "no 'variants' in product JSON"
|
|
230
|
+
elif kind in ("woo_store_api", "wp_rest"):
|
|
231
|
+
if isinstance(data, list):
|
|
232
|
+
result.status = "ok"
|
|
233
|
+
result.items_seen = len(data)
|
|
234
|
+
result.page_size = WOO_PAGE_SIZE if kind == "woo_store_api" else WP_PAGE_SIZE
|
|
235
|
+
result.fields = _fields(data[0]) if data else []
|
|
236
|
+
total = lowered.get("x-wp-total", "")
|
|
237
|
+
if total.isdigit():
|
|
238
|
+
result.total_items = int(total)
|
|
239
|
+
else:
|
|
240
|
+
result.status = "invalid"
|
|
241
|
+
result.note = "expected a JSON list"
|
|
242
|
+
elif kind == "json_feed":
|
|
243
|
+
items = data.get("items") if isinstance(data, dict) else None
|
|
244
|
+
if isinstance(items, list):
|
|
245
|
+
result.status = "ok"
|
|
246
|
+
result.items_seen = len(items)
|
|
247
|
+
result.page_size = len(items) or None
|
|
248
|
+
result.fields = _fields(items[0]) if items else []
|
|
249
|
+
else:
|
|
250
|
+
result.status = "invalid"
|
|
251
|
+
result.note = "no 'items' list"
|
|
252
|
+
else: # generic JSON link
|
|
253
|
+
result.status = "ok"
|
|
254
|
+
if isinstance(data, list):
|
|
255
|
+
result.items_seen = len(data)
|
|
256
|
+
result.fields = _fields(data[0]) if data else []
|
|
257
|
+
else:
|
|
258
|
+
result.fields = _fields(data)
|
|
259
|
+
return result
|