omnirank 0.5.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.
- omnirank/__init__.py +14 -0
- omnirank/__main__.py +6 -0
- omnirank/adapters/__init__.py +202 -0
- omnirank/adapters/astro.py +338 -0
- omnirank/adapters/base.py +372 -0
- omnirank/adapters/html.py +561 -0
- omnirank/adapters/jsx.py +340 -0
- omnirank/adapters/nextjs.py +692 -0
- omnirank/aeo/__init__.py +9 -0
- omnirank/aeo/extract.py +383 -0
- omnirank/aeo/propose.py +84 -0
- omnirank/aeo/rules.py +964 -0
- omnirank/aeo/runner.py +148 -0
- omnirank/applicability.py +98 -0
- omnirank/apply/__init__.py +23 -0
- omnirank/apply/engine.py +1254 -0
- omnirank/apply/journal.py +139 -0
- omnirank/apply/patch.py +144 -0
- omnirank/audit.py +185 -0
- omnirank/bands.py +106 -0
- omnirank/brief/__init__.py +0 -0
- omnirank/brief/analyze.py +197 -0
- omnirank/brief/constants.py +89 -0
- omnirank/brief/cost.py +62 -0
- omnirank/brief/egress.py +23 -0
- omnirank/brief/fetchpages.py +239 -0
- omnirank/brief/render.py +151 -0
- omnirank/brief/runner.py +369 -0
- omnirank/brief/serp.py +274 -0
- omnirank/brief/text.py +181 -0
- omnirank/cli.py +844 -0
- omnirank/clock.py +22 -0
- omnirank/cms/__init__.py +1 -0
- omnirank/cms/runner.py +170 -0
- omnirank/cms/wordpress.py +495 -0
- omnirank/cms/wordpress_apply.py +508 -0
- omnirank/cms/wordpress_plan.py +280 -0
- omnirank/config.py +81 -0
- omnirank/connect/__init__.py +4 -0
- omnirank/connect/bing.py +284 -0
- omnirank/connect/cloud_setup.py +43 -0
- omnirank/connect/confirm.py +242 -0
- omnirank/connect/constants.py +226 -0
- omnirank/connect/doctor.py +270 -0
- omnirank/connect/ga4.py +749 -0
- omnirank/connect/ga4_ai.py +123 -0
- omnirank/connect/google_auth.py +657 -0
- omnirank/connect/gsc.py +630 -0
- omnirank/connect/gsc_reports.py +169 -0
- omnirank/connect/http.py +310 -0
- omnirank/connect/indexnow.py +373 -0
- omnirank/connect/naver.py +536 -0
- omnirank/connect/runner.py +515 -0
- omnirank/connect/runner_ga4_ai.py +59 -0
- omnirank/connect/runner_more.py +489 -0
- omnirank/connect/runner_regional.py +260 -0
- omnirank/connect/secrets.py +190 -0
- omnirank/connect/urlcheck.py +41 -0
- omnirank/connect/yandex.py +350 -0
- omnirank/crawl/__init__.py +11 -0
- omnirank/crawl/analyze.py +493 -0
- omnirank/crawl/crawler.py +491 -0
- omnirank/crawl/custom.py +175 -0
- omnirank/crawl/export.py +67 -0
- omnirank/crawl/fetcher.py +212 -0
- omnirank/crawl/parse.py +102 -0
- omnirank/crawl/render.py +148 -0
- omnirank/crawl/robotsgate.py +198 -0
- omnirank/crawl/runner.py +295 -0
- omnirank/crawl/sitemap.py +99 -0
- omnirank/crawl/text.py +20 -0
- omnirank/crawl/urls.py +100 -0
- omnirank/crawlers.py +564 -0
- omnirank/data/ai_crawlers.json +269 -0
- omnirank/data/ai_referrers.json +42 -0
- omnirank/fetch.py +107 -0
- omnirank/fixes/__init__.py +92 -0
- omnirank/fixes/base.py +232 -0
- omnirank/fixes/canonical.py +243 -0
- omnirank/fixes/schema.py +126 -0
- omnirank/formats.py +134 -0
- omnirank/framework.py +223 -0
- omnirank/gates/__init__.py +48 -0
- omnirank/gates/aeo.py +114 -0
- omnirank/gates/contradictions.py +280 -0
- omnirank/gates/crawler_policy.py +85 -0
- omnirank/gates/geo.py +152 -0
- omnirank/gates/hygiene.py +81 -0
- omnirank/gates/jsonld.py +282 -0
- omnirank/gates/onpage.py +177 -0
- omnirank/gates/perf.py +115 -0
- omnirank/gates/security.py +264 -0
- omnirank/gates/seo.py +118 -0
- omnirank/gates/site.py +248 -0
- omnirank/geo_artifacts.py +199 -0
- omnirank/html.py +79 -0
- omnirank/keywords/__init__.py +5 -0
- omnirank/keywords/constants.py +69 -0
- omnirank/keywords/engine.py +384 -0
- omnirank/keywords/report.py +143 -0
- omnirank/keywords/runner.py +160 -0
- omnirank/keywords/source.py +60 -0
- omnirank/keywords/text.py +45 -0
- omnirank/locator.py +480 -0
- omnirank/logs/__init__.py +0 -0
- omnirank/logs/analyze.py +127 -0
- omnirank/logs/bots.py +69 -0
- omnirank/logs/ipranges.py +191 -0
- omnirank/logs/parse.py +452 -0
- omnirank/logs/paths.py +22 -0
- omnirank/logs/privacy.py +105 -0
- omnirank/logs/runner.py +179 -0
- omnirank/mcp_server.py +1480 -0
- omnirank/netguard.py +525 -0
- omnirank/packs/__init__.py +6 -0
- omnirank/packs/backlinks.py +535 -0
- omnirank/packs/blog.py +544 -0
- omnirank/packs/blog_cross.py +468 -0
- omnirank/packs/crawlers.py +23 -0
- omnirank/packs/entity.py +492 -0
- omnirank/packs/feeds.py +150 -0
- omnirank/packs/frontmatter.py +59 -0
- omnirank/packs/gsc.py +421 -0
- omnirank/packs/local.py +879 -0
- omnirank/packs/mdscan.py +326 -0
- omnirank/packs/miniyaml.py +378 -0
- omnirank/packs/model.py +46 -0
- omnirank/packs/product.py +979 -0
- omnirank/packs/refresh.py +165 -0
- omnirank/packs/runner.py +277 -0
- omnirank/packs/sitescan.py +294 -0
- omnirank/packs/textsafe.py +79 -0
- omnirank/packs/xmlsafe.py +92 -0
- omnirank/page.py +42 -0
- omnirank/registry.py +302 -0
- omnirank/report.py +251 -0
- omnirank/report_cmd/__init__.py +7 -0
- omnirank/report_cmd/delta.py +58 -0
- omnirank/report_cmd/files.py +64 -0
- omnirank/report_cmd/model.py +208 -0
- omnirank/report_cmd/notify.py +195 -0
- omnirank/report_cmd/pdf.py +83 -0
- omnirank/report_cmd/portfolio.py +342 -0
- omnirank/report_cmd/render.py +379 -0
- omnirank/report_cmd/runner.py +267 -0
- omnirank/robots.py +172 -0
- omnirank/scanner/__init__.py +10 -0
- omnirank/scanner/badge.py +90 -0
- omnirank/scanner/cache.py +69 -0
- omnirank/scanner/cli.py +96 -0
- omnirank/scanner/engine.py +289 -0
- omnirank/scanner/limits.py +98 -0
- omnirank/scanner/server.py +143 -0
- omnirank/scanner/service.py +328 -0
- omnirank/schema/__init__.py +13 -0
- omnirank/schema/catalog.py +679 -0
- omnirank/schema/catalog_specs.py +350 -0
- omnirank/schema/core.py +306 -0
- omnirank/schema/extract.py +396 -0
- omnirank/schema/gate.py +121 -0
- omnirank/schema/runner.py +213 -0
- omnirank/schema/validate.py +504 -0
- omnirank/schema/vocab.py +305 -0
- omnirank/schemas/omnirank.config.schema.json +268 -0
- omnirank/track/__init__.py +0 -0
- omnirank/track/ai_prompts.py +207 -0
- omnirank/track/analysis.py +197 -0
- omnirank/track/constants.py +155 -0
- omnirank/track/cost.py +229 -0
- omnirank/track/discover.py +277 -0
- omnirank/track/discover_cli.py +309 -0
- omnirank/track/discover_constants.py +95 -0
- omnirank/track/engines.py +216 -0
- omnirank/track/estimate_view.py +212 -0
- omnirank/track/history.py +261 -0
- omnirank/track/runner.py +586 -0
- omnirank/track/stats.py +138 -0
- omnirank/track/storage.py +128 -0
- omnirank-0.5.0.dist-info/METADATA +47 -0
- omnirank-0.5.0.dist-info/RECORD +183 -0
- omnirank-0.5.0.dist-info/WHEEL +5 -0
- omnirank-0.5.0.dist-info/entry_points.txt +2 -0
- omnirank-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
"""The crawl loop: robots.txt, sitemaps, breadth-first link discovery, redirect chains.
|
|
2
|
+
|
|
3
|
+
Deterministic by construction: URLs are fetched level by level, a level's GETs may run in
|
|
4
|
+
parallel (``concurrency``) but results are consumed in discovery order, and redirect hops
|
|
5
|
+
are followed sequentially. Every request goes through ``Fetcher.get`` (egress policy, rate
|
|
6
|
+
limit, byte cap); every URL (including each redirect hop) is checked against robots.txt
|
|
7
|
+
and the same-site rule before it is requested.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Callable, Iterable
|
|
15
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
16
|
+
from dataclasses import asdict, dataclass, field
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from ..mcp_server import EgressPolicy, PolicyError
|
|
21
|
+
from .custom import Extractor, ExtractRunner
|
|
22
|
+
from .fetcher import Fetcher, RateLimiter, Response
|
|
23
|
+
from .parse import parse_page
|
|
24
|
+
from .render import Renderer, SubrequestGuard
|
|
25
|
+
from .robotsgate import MAX_ROBOTS_BYTES, RobotsGate
|
|
26
|
+
from .sitemap import SitemapResult, collect
|
|
27
|
+
from .text import clean
|
|
28
|
+
from .urls import host_of, normalize, origin, same_site
|
|
29
|
+
|
|
30
|
+
HTML_TYPES = ("text/html", "application/xhtml+xml")
|
|
31
|
+
MAX_EXTRACT_TIMEOUTS = 3
|
|
32
|
+
EXTERNAL_MAX_BYTES = 65536
|
|
33
|
+
MAX_EXTERNAL_TOTAL = 200
|
|
34
|
+
MAX_LINKS_TOTAL = 200_000 # links kept for the report (discovery is not cut)
|
|
35
|
+
MAX_ROBOTS_REDIRECTS = 5 # RFC 9309 2.3.1.2
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CrawlAborted(Exception):
|
|
39
|
+
"""An unexpected error stopped the crawl; ``result`` holds what was gathered."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, result, error: BaseException):
|
|
42
|
+
super().__init__(str(error))
|
|
43
|
+
self.result, self.error = result, error
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CrawlError(Exception):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _bounded(name: str, value, low, high):
|
|
51
|
+
if not low <= value <= high:
|
|
52
|
+
raise ValueError(f"{name} must be between {low} and {high}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class CrawlConfig:
|
|
57
|
+
start_url: str
|
|
58
|
+
max_urls: int = 500
|
|
59
|
+
max_depth: int = 10
|
|
60
|
+
delay: float = 1.0
|
|
61
|
+
concurrency: int = 2
|
|
62
|
+
max_redirects: int = 5
|
|
63
|
+
max_page_bytes: int = 5_000_000
|
|
64
|
+
max_total_bytes: int = 500_000_000
|
|
65
|
+
max_seconds: float = 1800.0
|
|
66
|
+
timeout: float = 15.0
|
|
67
|
+
check_external: bool = False
|
|
68
|
+
external_per_host: int = 5
|
|
69
|
+
|
|
70
|
+
def __post_init__(self):
|
|
71
|
+
_bounded("max_urls", self.max_urls, 1, 100_000)
|
|
72
|
+
_bounded("max_depth", self.max_depth, 0, 100)
|
|
73
|
+
_bounded("delay", self.delay, 0, 60)
|
|
74
|
+
_bounded("concurrency", self.concurrency, 1, 8)
|
|
75
|
+
_bounded("max_redirects", self.max_redirects, 0, 20)
|
|
76
|
+
_bounded("max_page_bytes", self.max_page_bytes, 100, 50_000_000)
|
|
77
|
+
_bounded("max_total_bytes", self.max_total_bytes, 100, 10_000_000_000)
|
|
78
|
+
_bounded("max_seconds", self.max_seconds, 0.001, 86_400)
|
|
79
|
+
_bounded("timeout", self.timeout, 0.1, 300)
|
|
80
|
+
_bounded("external_per_host", self.external_per_host, 1, 100)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class CrawlResult:
|
|
85
|
+
start_url: str
|
|
86
|
+
site_host: str
|
|
87
|
+
config: dict
|
|
88
|
+
robots: dict
|
|
89
|
+
sitemap: SitemapResult
|
|
90
|
+
records: dict[str, dict] = field(default_factory=dict)
|
|
91
|
+
links: list[dict] = field(default_factory=list)
|
|
92
|
+
redirect_edges: list[tuple[str, str]] = field(default_factory=list)
|
|
93
|
+
tokens: dict[str, list[str]] = field(default_factory=dict)
|
|
94
|
+
blocked_by_robots: list[str] = field(default_factory=list)
|
|
95
|
+
probe: dict | None = None
|
|
96
|
+
external: list[dict] = field(default_factory=list)
|
|
97
|
+
exhausted: str | None = None
|
|
98
|
+
bytes_downloaded: int = 0
|
|
99
|
+
rendered: bool = False
|
|
100
|
+
links_truncated: bool = False
|
|
101
|
+
content_hashes: dict[str, str] = field(default_factory=dict)
|
|
102
|
+
aborted: str | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def crawl(cfg: CrawlConfig, *, transport: httpx.BaseTransport, policy: EgressPolicy,
|
|
106
|
+
renderer: Renderer | None = None, extractors: Iterable[Extractor] = (),
|
|
107
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
108
|
+
now: Callable[[], float] = time.monotonic,
|
|
109
|
+
extract_budget: float = 2.0) -> CrawlResult:
|
|
110
|
+
start = normalize(cfg.start_url)
|
|
111
|
+
if start is None:
|
|
112
|
+
raise CrawlError("the start URL must be an absolute http(s) URL without user info")
|
|
113
|
+
try:
|
|
114
|
+
policy.check_url(start)
|
|
115
|
+
except PolicyError as exc:
|
|
116
|
+
raise CrawlError(str(exc)) from None
|
|
117
|
+
run = _Crawl(cfg, start, transport, policy, renderer, list(extractors), sleep, now,
|
|
118
|
+
extract_budget)
|
|
119
|
+
try:
|
|
120
|
+
return run.run()
|
|
121
|
+
except Exception as exc: # keep what was crawled; re-raised as CrawlAborted
|
|
122
|
+
if run.result is None:
|
|
123
|
+
raise
|
|
124
|
+
run.result.aborted = clean(f"{type(exc).__name__}: {exc}", 300)
|
|
125
|
+
raise CrawlAborted(run.result, exc) from exc
|
|
126
|
+
finally:
|
|
127
|
+
run.close()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _Crawl:
|
|
131
|
+
def __init__(self, cfg, start, transport, policy, renderer, extractors, sleep, now,
|
|
132
|
+
extract_budget):
|
|
133
|
+
self.cfg, self.start, self.renderer, self.extractors = cfg, start, renderer, extractors
|
|
134
|
+
self.now = now
|
|
135
|
+
self.deadline = now() + cfg.max_seconds
|
|
136
|
+
self.limiter = RateLimiter(cfg.delay, sleep=sleep, now=now)
|
|
137
|
+
self.fetcher = Fetcher(transport, policy, limiter=self.limiter,
|
|
138
|
+
max_bytes=cfg.max_page_bytes, timeout=cfg.timeout)
|
|
139
|
+
self.site_host = host_of(start)
|
|
140
|
+
self.extract_runner = ExtractRunner(extract_budget) if extractors else None
|
|
141
|
+
self.extract_timeouts: dict[str, int] = {}
|
|
142
|
+
self.locations: dict[str, str] = {} # raw Location header per 3xx URL
|
|
143
|
+
self.result: CrawlResult | None = None
|
|
144
|
+
self.gate: RobotsGate | None = None
|
|
145
|
+
self.queued: set[str] = set()
|
|
146
|
+
self.lock = threading.Lock()
|
|
147
|
+
|
|
148
|
+
def close(self) -> None:
|
|
149
|
+
self.fetcher.close()
|
|
150
|
+
if self.extract_runner is not None:
|
|
151
|
+
self.extract_runner.close()
|
|
152
|
+
|
|
153
|
+
# --- requests -------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
def _get(self, url: str, max_bytes: int | None = None) -> Response | None:
|
|
156
|
+
"""One request, or None once a budget is exhausted (nothing is sent then)."""
|
|
157
|
+
res = self.result
|
|
158
|
+
if res.exhausted in ("time", "bytes"): # max-urls only stops new pages
|
|
159
|
+
return None
|
|
160
|
+
if self.now() > self.deadline:
|
|
161
|
+
with self.lock:
|
|
162
|
+
res.exhausted = res.exhausted or "time"
|
|
163
|
+
return None
|
|
164
|
+
resp = self.fetcher.get(url, max_bytes)
|
|
165
|
+
with self.lock: # _get runs in worker threads
|
|
166
|
+
res.bytes_downloaded += len(resp.body)
|
|
167
|
+
if res.bytes_downloaded > self.cfg.max_total_bytes:
|
|
168
|
+
res.exhausted = "bytes"
|
|
169
|
+
return resp
|
|
170
|
+
|
|
171
|
+
# --- main ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
def run(self) -> CrawlResult:
|
|
174
|
+
cfg, start = self.cfg, self.start
|
|
175
|
+
site = origin(start)
|
|
176
|
+
self.result = res = CrawlResult(
|
|
177
|
+
start_url=start, site_host=self.site_host,
|
|
178
|
+
config={k: v for k, v in asdict(cfg).items() if k != "start_url"},
|
|
179
|
+
robots={}, sitemap=SitemapResult(), rendered=self.renderer is not None)
|
|
180
|
+
self.gate = self._robots(f"{site}/robots.txt")
|
|
181
|
+
res.robots = self.gate.to_dict()
|
|
182
|
+
if self.renderer is not None and hasattr(self.renderer, "bind"):
|
|
183
|
+
self.renderer.bind(SubrequestGuard(self._subfetch, self.site_host))
|
|
184
|
+
if self.gate.crawl_delay and self.gate.crawl_delay > self.limiter.interval:
|
|
185
|
+
self.limiter.interval = self.gate.crawl_delay
|
|
186
|
+
|
|
187
|
+
res.sitemap = collect(self._get_or_empty, self.gate.sitemaps, f"{site}/sitemap.xml",
|
|
188
|
+
self.site_host, self.gate.allowed)
|
|
189
|
+
|
|
190
|
+
self._bfs([(start, 0)], source="start")
|
|
191
|
+
seeds = [u for u in res.sitemap.urls if u not in self.queued]
|
|
192
|
+
self._bfs([(u, 0) for u in seeds], source="sitemap")
|
|
193
|
+
|
|
194
|
+
probe = f"{site}/omnirank-404-probe-{hashlib.sha256(start.encode()).hexdigest()[:12]}"
|
|
195
|
+
if self.gate.allowed(probe):
|
|
196
|
+
resp = self._get(probe)
|
|
197
|
+
if resp is not None:
|
|
198
|
+
res.probe = {"url": probe, "status": resp.status}
|
|
199
|
+
if cfg.check_external:
|
|
200
|
+
self._check_external()
|
|
201
|
+
return res
|
|
202
|
+
|
|
203
|
+
def _robots(self, url: str) -> RobotsGate:
|
|
204
|
+
"""Fetch robots.txt, following up to 5 redirects (RFC 9309 2.3.1.2). Every hop goes
|
|
205
|
+
through the egress policy; hops may leave the host (the RFC allows it) and the
|
|
206
|
+
rules still apply to the crawled site. A loop or more than 5 hops = "unavailable"
|
|
207
|
+
(allow all, 2.3.1.3); a refused or failed hop = "unreachable" (disallow all)."""
|
|
208
|
+
seen = [url]
|
|
209
|
+
hops: list[str] = []
|
|
210
|
+
current = url
|
|
211
|
+
while True:
|
|
212
|
+
resp = self._get(current, MAX_ROBOTS_BYTES)
|
|
213
|
+
if resp is None or resp.status == 0:
|
|
214
|
+
gate = RobotsGate.from_response(0, "")
|
|
215
|
+
gate.reason = "unreachable" if resp is None or not resp.blocked \
|
|
216
|
+
else "redirect-refused-by-egress-policy"
|
|
217
|
+
break
|
|
218
|
+
if not 300 <= resp.status < 400:
|
|
219
|
+
gate = RobotsGate.from_response(resp.status, resp.text())
|
|
220
|
+
break
|
|
221
|
+
nxt = normalize(resp.headers.get("location", ""), current)
|
|
222
|
+
if nxt is None or nxt in seen or len(hops) >= MAX_ROBOTS_REDIRECTS:
|
|
223
|
+
gate = RobotsGate.from_response(404, "")
|
|
224
|
+
gate.reason = ("invalid-redirect" if nxt is None else
|
|
225
|
+
"redirect-loop" if nxt in seen else "too-many-redirects")
|
|
226
|
+
break
|
|
227
|
+
hops.append(nxt)
|
|
228
|
+
seen.append(nxt)
|
|
229
|
+
current = nxt
|
|
230
|
+
gate.redirects = hops
|
|
231
|
+
return gate
|
|
232
|
+
|
|
233
|
+
def _subfetch(self, url: str) -> Response | None:
|
|
234
|
+
"""A browser sub-request, fetched by the crawl itself (egress policy incl. the
|
|
235
|
+
connect-time check, rate limit, byte cap, robots.txt); never follows redirects."""
|
|
236
|
+
target = normalize(url)
|
|
237
|
+
if target is None or not same_site(target, self.site_host) or \
|
|
238
|
+
not self.gate.allowed(target):
|
|
239
|
+
return None
|
|
240
|
+
resp = self._get(target)
|
|
241
|
+
if resp is None or resp.status == 0:
|
|
242
|
+
return None
|
|
243
|
+
return resp
|
|
244
|
+
|
|
245
|
+
def _get_or_empty(self, url: str, max_bytes: int) -> Response:
|
|
246
|
+
resp = self._get(url, max_bytes)
|
|
247
|
+
return resp if resp is not None else Response(url, 0, {}, b"", False, 0,
|
|
248
|
+
error="crawl budget exhausted")
|
|
249
|
+
|
|
250
|
+
def _bfs(self, frontier: list[tuple[str, int]], *, source: str) -> None:
|
|
251
|
+
res, cfg = self.result, self.cfg
|
|
252
|
+
pool = ThreadPoolExecutor(max_workers=cfg.concurrency) if cfg.concurrency > 1 else None
|
|
253
|
+
try:
|
|
254
|
+
for url, _ in frontier:
|
|
255
|
+
if url not in self.queued:
|
|
256
|
+
self.queued.add(url)
|
|
257
|
+
level_source = source
|
|
258
|
+
while frontier and not res.exhausted:
|
|
259
|
+
batch: list[tuple[str, int]] = []
|
|
260
|
+
full = False
|
|
261
|
+
for url, depth in frontier:
|
|
262
|
+
if url in res.records:
|
|
263
|
+
continue
|
|
264
|
+
if not self.gate.allowed(url):
|
|
265
|
+
if url not in res.blocked_by_robots:
|
|
266
|
+
res.blocked_by_robots.append(url)
|
|
267
|
+
continue
|
|
268
|
+
if len(res.records) + len(batch) >= cfg.max_urls:
|
|
269
|
+
full = True # set after this batch is fetched
|
|
270
|
+
break
|
|
271
|
+
batch.append((url, depth))
|
|
272
|
+
urls = [u for u, _ in batch]
|
|
273
|
+
responses = list(pool.map(self._get, urls)) if pool else \
|
|
274
|
+
[self._get(u) for u in urls]
|
|
275
|
+
nxt: list[tuple[str, int]] = []
|
|
276
|
+
for (url, depth), resp in zip(batch, responses, strict=True):
|
|
277
|
+
if resp is None or url in res.records:
|
|
278
|
+
continue
|
|
279
|
+
targets = self._process(url, resp, depth, level_source)
|
|
280
|
+
if 300 <= resp.status < 400:
|
|
281
|
+
targets += self._follow(url, resp, depth)
|
|
282
|
+
if depth + 1 > cfg.max_depth:
|
|
283
|
+
continue
|
|
284
|
+
for target in targets:
|
|
285
|
+
if target not in self.queued:
|
|
286
|
+
self.queued.add(target)
|
|
287
|
+
nxt.append((target, depth + 1))
|
|
288
|
+
frontier = nxt
|
|
289
|
+
level_source = "link"
|
|
290
|
+
if full:
|
|
291
|
+
res.exhausted = res.exhausted or "max-urls"
|
|
292
|
+
finally:
|
|
293
|
+
if pool is not None:
|
|
294
|
+
pool.shutdown(wait=True)
|
|
295
|
+
|
|
296
|
+
# --- one page -----------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
def _process(self, url: str, resp: Response, depth: int, source: str) -> list[str]:
|
|
299
|
+
"""Record ``resp`` under ``url``; return the followable internal links found."""
|
|
300
|
+
res = self.result
|
|
301
|
+
rec: dict = {
|
|
302
|
+
"url": url, "source": source, "crawl_depth": depth, "status": resp.status,
|
|
303
|
+
"error": resp.error, "blocked_by_policy": resp.blocked,
|
|
304
|
+
"content_type": resp.content_type or None, "bytes": len(resp.body),
|
|
305
|
+
"truncated": resp.truncated, "elapsed_ms": resp.elapsed_ms,
|
|
306
|
+
"x_robots_tag": clean(resp.headers["x-robots-tag"], 200).lower()
|
|
307
|
+
if "x-robots-tag" in resp.headers else None,
|
|
308
|
+
"location": clean(resp.headers["location"], 2048)
|
|
309
|
+
if 300 <= resp.status < 400 and "location" in resp.headers else None,
|
|
310
|
+
"skipped": resp.skipped,
|
|
311
|
+
"parsed": False, "title": None, "h1": [], "description": None,
|
|
312
|
+
"canonical": None, "meta_robots": None, "hreflang": [], "word_count": None,
|
|
313
|
+
"images_missing_alt": [], "images_missing_dimensions": [], "redirect": None,
|
|
314
|
+
}
|
|
315
|
+
res.records[url] = rec
|
|
316
|
+
if 300 <= resp.status < 400 and "location" in resp.headers:
|
|
317
|
+
self.locations[url] = resp.headers["location"]
|
|
318
|
+
if not (200 <= resp.status < 300 and resp.content_type in HTML_TYPES
|
|
319
|
+
and not resp.truncated and resp.body):
|
|
320
|
+
return []
|
|
321
|
+
html = resp.text()
|
|
322
|
+
rendered_html = html
|
|
323
|
+
if self.renderer is not None:
|
|
324
|
+
try:
|
|
325
|
+
rendered_html = self.renderer.render(url, html)
|
|
326
|
+
rec["rendered"] = True
|
|
327
|
+
rec["raw_word_count"] = len(parse_page(url, html).tokens)
|
|
328
|
+
except Exception as exc: # noqa: BLE001 - a browser failure must not stop the crawl
|
|
329
|
+
rec["rendered"] = False
|
|
330
|
+
rec["render_error"] = clean(exc, 200)
|
|
331
|
+
info = parse_page(url, rendered_html)
|
|
332
|
+
rec.update(parsed=True, title=info.title, h1=info.h1, description=info.description,
|
|
333
|
+
canonical=info.canonical, meta_robots=info.meta_robots,
|
|
334
|
+
hreflang=info.hreflang, word_count=len(info.tokens),
|
|
335
|
+
images_missing_alt=info.images_missing_alt,
|
|
336
|
+
images_missing_dimensions=info.images_missing_dimensions)
|
|
337
|
+
res.tokens[url] = info.tokens
|
|
338
|
+
res.content_hashes[url] = info.content_hash
|
|
339
|
+
if self.extractors:
|
|
340
|
+
self._extract(rec, rendered_html)
|
|
341
|
+
page_nofollow = any(t in ("nofollow", "none") for t in robots_directives(rec))
|
|
342
|
+
followable = []
|
|
343
|
+
for link in info.links:
|
|
344
|
+
internal = same_site(link.target, self.site_host)
|
|
345
|
+
if len(res.links) < MAX_LINKS_TOTAL:
|
|
346
|
+
res.links.append({"source": url, "target": link.target, "text": link.text,
|
|
347
|
+
"rel": link.rel, "internal": internal})
|
|
348
|
+
else:
|
|
349
|
+
res.links_truncated = True
|
|
350
|
+
if internal and not page_nofollow and "nofollow" not in link.rel:
|
|
351
|
+
followable.append(link.target)
|
|
352
|
+
# hreflang alternates on this site are crawled too, so they can be checked
|
|
353
|
+
followable += [a["href"] for a in info.hreflang
|
|
354
|
+
if a["href"] and same_site(a["href"], self.site_host)]
|
|
355
|
+
if info.canonical and same_site(info.canonical, self.site_host):
|
|
356
|
+
followable.append(info.canonical) # so the canonical target can be checked
|
|
357
|
+
return followable
|
|
358
|
+
|
|
359
|
+
def _extract(self, rec: dict, html: str) -> None:
|
|
360
|
+
"""CSS, XPath and regex all run in the killable worker with a per-page budget."""
|
|
361
|
+
values: dict = {}
|
|
362
|
+
errors: dict = {}
|
|
363
|
+
for ex in self.extractors:
|
|
364
|
+
if self.extract_timeouts.get(ex.name, 0) >= MAX_EXTRACT_TIMEOUTS:
|
|
365
|
+
values[ex.name] = None
|
|
366
|
+
errors[ex.name] = "disabled-after-timeouts"
|
|
367
|
+
continue
|
|
368
|
+
try:
|
|
369
|
+
found = self.extract_runner.run(ex.kind, ex.expr, html)
|
|
370
|
+
except RuntimeError as exc:
|
|
371
|
+
values[ex.name] = None
|
|
372
|
+
errors[ex.name] = clean(exc, 120)
|
|
373
|
+
continue
|
|
374
|
+
values[ex.name] = found
|
|
375
|
+
if found is None:
|
|
376
|
+
errors[ex.name] = "timeout"
|
|
377
|
+
self.extract_timeouts[ex.name] = self.extract_timeouts.get(ex.name, 0) + 1
|
|
378
|
+
rec["extract"] = values
|
|
379
|
+
if errors:
|
|
380
|
+
rec["extract_errors"] = errors
|
|
381
|
+
|
|
382
|
+
# --- redirects ----------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
def _follow(self, url: str, resp: Response, depth: int) -> list[str]:
|
|
385
|
+
"""Follow ``url``'s redirect chain hop by hop, re-validating every hop."""
|
|
386
|
+
res, cfg = self.result, self.cfg
|
|
387
|
+
chain = [{"url": url, "status": resp.status}]
|
|
388
|
+
current, location = url, self.locations.get(url)
|
|
389
|
+
result, final, hops, targets = "ok", url, 0, []
|
|
390
|
+
while True:
|
|
391
|
+
if not location:
|
|
392
|
+
result = "no-location"
|
|
393
|
+
break
|
|
394
|
+
nxt = normalize(location, current)
|
|
395
|
+
if nxt is None:
|
|
396
|
+
result, final = "invalid-location", clean(location, 300)
|
|
397
|
+
break
|
|
398
|
+
hops += 1
|
|
399
|
+
final = nxt
|
|
400
|
+
if any(h["url"] == nxt for h in chain):
|
|
401
|
+
result = "loop"
|
|
402
|
+
break
|
|
403
|
+
if hops > cfg.max_redirects:
|
|
404
|
+
result = "too-many-hops"
|
|
405
|
+
break
|
|
406
|
+
if not same_site(nxt, self.site_host):
|
|
407
|
+
result = "offsite"
|
|
408
|
+
break
|
|
409
|
+
if not self.gate.allowed(nxt):
|
|
410
|
+
result = "blocked-by-robots"
|
|
411
|
+
break
|
|
412
|
+
res.redirect_edges.append((current, nxt))
|
|
413
|
+
rec = res.records.get(nxt)
|
|
414
|
+
if rec is None:
|
|
415
|
+
if len(res.records) >= cfg.max_urls:
|
|
416
|
+
res.exhausted = res.exhausted or "max-urls"
|
|
417
|
+
result = "budget"
|
|
418
|
+
break
|
|
419
|
+
hop = self._get(nxt)
|
|
420
|
+
if hop is None:
|
|
421
|
+
result = "budget"
|
|
422
|
+
break
|
|
423
|
+
if hop.blocked:
|
|
424
|
+
result = "blocked-by-policy"
|
|
425
|
+
break
|
|
426
|
+
self.queued.add(nxt)
|
|
427
|
+
targets += self._process(nxt, hop, depth + hops, "redirect")
|
|
428
|
+
rec = res.records[nxt]
|
|
429
|
+
chain.append({"url": nxt, "status": rec["status"]})
|
|
430
|
+
if not 300 <= rec["status"] < 400:
|
|
431
|
+
break
|
|
432
|
+
current, location = nxt, self.locations.get(nxt)
|
|
433
|
+
res.records[url]["redirect"] = {"chain": chain, "hops": hops, "result": result,
|
|
434
|
+
"final_url": final}
|
|
435
|
+
return targets
|
|
436
|
+
|
|
437
|
+
# --- optional external link check ---------------------------------------------------
|
|
438
|
+
|
|
439
|
+
def _check_external(self) -> None:
|
|
440
|
+
res, cfg = self.result, self.cfg
|
|
441
|
+
per_host: dict[str, int] = {}
|
|
442
|
+
gates: dict[str, RobotsGate | None] = {}
|
|
443
|
+
seen: set[str] = set()
|
|
444
|
+
for link in res.links:
|
|
445
|
+
target = link["target"]
|
|
446
|
+
if link["internal"] or target in seen or len(res.external) >= MAX_EXTERNAL_TOTAL:
|
|
447
|
+
continue
|
|
448
|
+
seen.add(target)
|
|
449
|
+
host = host_of(target)
|
|
450
|
+
if per_host.get(host, 0) >= cfg.external_per_host:
|
|
451
|
+
continue
|
|
452
|
+
per_host[host] = per_host.get(host, 0) + 1
|
|
453
|
+
if host not in gates:
|
|
454
|
+
robots = self._get(f"{origin(target)}/robots.txt", MAX_ROBOTS_BYTES)
|
|
455
|
+
if robots is None:
|
|
456
|
+
return
|
|
457
|
+
gates[host] = None if robots.blocked else \
|
|
458
|
+
RobotsGate.from_response(robots.status, robots.text())
|
|
459
|
+
if gates[host] is None: # the host itself is refused (SSRF)
|
|
460
|
+
res.external.append({"url": target, "status": None,
|
|
461
|
+
"result": "blocked-by-policy"})
|
|
462
|
+
continue
|
|
463
|
+
if not gates[host].allowed(target):
|
|
464
|
+
res.external.append({"url": target, "status": None,
|
|
465
|
+
"result": "blocked-by-robots"})
|
|
466
|
+
continue
|
|
467
|
+
resp = self._get(target, EXTERNAL_MAX_BYTES)
|
|
468
|
+
if resp is None:
|
|
469
|
+
return
|
|
470
|
+
res.external.append({
|
|
471
|
+
"url": target, "status": resp.status,
|
|
472
|
+
"result": "blocked-by-policy" if resp.blocked else
|
|
473
|
+
("error" if resp.status == 0 else "ok"),
|
|
474
|
+
"error": resp.error})
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _tokens(value: str | None) -> list[str]:
|
|
478
|
+
"""Robots directives from a meta robots / X-Robots-Tag value; an ``agent:`` prefix
|
|
479
|
+
(``googlebot: noindex``) is dropped."""
|
|
480
|
+
if not value:
|
|
481
|
+
return []
|
|
482
|
+
out = []
|
|
483
|
+
for part in value.replace(";", ",").split(","):
|
|
484
|
+
token = part.rsplit(":", 1)[-1].strip().lower()
|
|
485
|
+
if token:
|
|
486
|
+
out.append(token)
|
|
487
|
+
return out
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def robots_directives(rec: dict) -> list[str]:
|
|
491
|
+
return _tokens(rec.get("meta_robots")) + _tokens(rec.get("x_robots_tag"))
|
omnirank/crawl/custom.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Custom extraction: ``name=css:SELECTOR``, ``name=xpath:EXPR`` or ``name=regex:PATTERN``.
|
|
2
|
+
|
|
3
|
+
Every kind runs in ONE separate worker process with a wall-clock budget per page and
|
|
4
|
+
extractor (default 2 s): Python's ``re`` cannot be interrupted mid-match (``(a+)+$``),
|
|
5
|
+
and an XPath such as ``//div[count(following::div) > count(preceding::div)]`` is
|
|
6
|
+
quadratic in the page size. On timeout the worker is killed and restarted and the value is
|
|
7
|
+
``None`` with the error ``timeout`` -- never a partial guess; after 3 timeouts the
|
|
8
|
+
extractor is disabled for the rest of the crawl.
|
|
9
|
+
|
|
10
|
+
Refused when parsed (before any request): expressions over 500 characters, regex
|
|
11
|
+
back-references, XPath ``document()``/``doc()``/``doc-available()``/``unparsed-text()``
|
|
12
|
+
/``collection()`` and every prefixed (extension) function such as ``php:function()`` or
|
|
13
|
+
``exsl:node-set()``. lxml is also given no extension functions, so a prefixed call would
|
|
14
|
+
fail anyway. Inputs: the first 1,000,000 characters of the page HTML (already capped by
|
|
15
|
+
``--max-page-bytes``); at most 100 regex matches and 20 values per extractor.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import multiprocessing
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
import soupsieve
|
|
24
|
+
from lxml import etree
|
|
25
|
+
|
|
26
|
+
from .text import clean
|
|
27
|
+
|
|
28
|
+
_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,39}")
|
|
29
|
+
_BACKREF = re.compile(r"\\[1-9]|\(\?P=")
|
|
30
|
+
_XPATH_EXTERNAL = re.compile(
|
|
31
|
+
r"(?<![\w.:-])(?:document|doc|doc-available|unparsed-text(?:-lines|-available)?|"
|
|
32
|
+
r"collection|uri-collection)\s*\(", re.IGNORECASE)
|
|
33
|
+
_XPATH_PREFIXED_CALL = re.compile(r"(?<![\w.:-])[A-Za-z_][\w.-]*:(?!:)[A-Za-z_][\w.-]*\s*\(")
|
|
34
|
+
MAX_PATTERN = 500
|
|
35
|
+
MAX_VALUES = 20
|
|
36
|
+
MAX_REGEX_MATCHES = 100
|
|
37
|
+
MAX_INPUT = 1_000_000
|
|
38
|
+
STARTUP_SECONDS = 60.0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ExtractError(ValueError):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Extractor:
|
|
47
|
+
name: str
|
|
48
|
+
kind: str # "css" | "xpath" | "regex"
|
|
49
|
+
expr: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_extractor(spec: str) -> Extractor:
|
|
53
|
+
name, sep, rest = spec.partition("=")
|
|
54
|
+
if not sep or not _NAME.fullmatch(name):
|
|
55
|
+
raise ExtractError(f"--extract {spec[:60]!r}: expected name=css:SEL, name=xpath:EXPR "
|
|
56
|
+
"or name=regex:PAT (name: letters, digits, '_' or '-')")
|
|
57
|
+
kind, sep, expr = rest.partition(":")
|
|
58
|
+
if not sep or kind not in ("css", "xpath", "regex") or not expr:
|
|
59
|
+
raise ExtractError(f"--extract {name}: the kind must be css:, xpath: or regex: "
|
|
60
|
+
"followed by an expression")
|
|
61
|
+
if len(expr) > MAX_PATTERN:
|
|
62
|
+
raise ExtractError(f"--extract {name}: expression longer than {MAX_PATTERN} characters")
|
|
63
|
+
if kind == "xpath" and (_XPATH_EXTERNAL.search(expr) or _XPATH_PREFIXED_CALL.search(expr)):
|
|
64
|
+
raise ExtractError(f"--extract {name}: XPath functions that load documents and "
|
|
65
|
+
"extension (prefixed) functions are not allowed")
|
|
66
|
+
if kind == "regex" and _BACKREF.search(expr):
|
|
67
|
+
raise ExtractError(f"--extract {name}: back-references are not supported")
|
|
68
|
+
try:
|
|
69
|
+
if kind == "css":
|
|
70
|
+
soupsieve.compile(expr)
|
|
71
|
+
elif kind == "xpath":
|
|
72
|
+
etree.XPath(expr)
|
|
73
|
+
else:
|
|
74
|
+
re.compile(expr)
|
|
75
|
+
except Exception as exc: # noqa: BLE001 - each library has its own error type
|
|
76
|
+
raise ExtractError(f"--extract {name}: invalid {kind} expression: "
|
|
77
|
+
f"{clean(exc, 120)}") from None
|
|
78
|
+
return Extractor(name, kind, expr)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# --- the worker (runs in the child process) ------------------------------------------------
|
|
82
|
+
|
|
83
|
+
def _evaluate(kind: str, expr: str, text: str) -> list[str]: # pragma: no cover - child
|
|
84
|
+
if kind == "regex":
|
|
85
|
+
out = []
|
|
86
|
+
for m in re.finditer(expr, text):
|
|
87
|
+
out.append(m.group(1) if m.re.groups else m.group(0))
|
|
88
|
+
if len(out) >= MAX_REGEX_MATCHES:
|
|
89
|
+
break
|
|
90
|
+
return [o or "" for o in out]
|
|
91
|
+
if kind == "css":
|
|
92
|
+
from bs4 import BeautifulSoup
|
|
93
|
+
soup = BeautifulSoup(text, "lxml")
|
|
94
|
+
return [el.get_text(" ") for el in soup.select(expr, limit=MAX_VALUES)]
|
|
95
|
+
from lxml import html as lxml_html
|
|
96
|
+
try:
|
|
97
|
+
doc = lxml_html.fromstring(text)
|
|
98
|
+
except (etree.ParserError, ValueError):
|
|
99
|
+
return []
|
|
100
|
+
result = etree.XPath(expr)(doc) # no extensions registered
|
|
101
|
+
if not isinstance(result, list):
|
|
102
|
+
return [str(result)]
|
|
103
|
+
return [item.text_content() if hasattr(item, "text_content") else str(item)
|
|
104
|
+
for item in result[:MAX_VALUES]]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _worker(conn) -> None: # pragma: no cover - runs in the child process
|
|
108
|
+
conn.send("ready")
|
|
109
|
+
while True:
|
|
110
|
+
try:
|
|
111
|
+
msg = conn.recv()
|
|
112
|
+
except EOFError:
|
|
113
|
+
return
|
|
114
|
+
if msg is None:
|
|
115
|
+
return
|
|
116
|
+
kind, expr, text = msg
|
|
117
|
+
try:
|
|
118
|
+
conn.send(_evaluate(kind, expr, text))
|
|
119
|
+
except Exception: # noqa: BLE001 - a bad expression on one page only
|
|
120
|
+
conn.send([])
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class ExtractRunner:
|
|
124
|
+
def __init__(self, budget_seconds: float = 2.0):
|
|
125
|
+
self.budget = budget_seconds
|
|
126
|
+
self._ctx = multiprocessing.get_context("spawn")
|
|
127
|
+
self._proc = None
|
|
128
|
+
self._conn = None
|
|
129
|
+
|
|
130
|
+
def _start(self) -> None:
|
|
131
|
+
parent, child = self._ctx.Pipe()
|
|
132
|
+
proc = self._ctx.Process(target=_worker, args=(child,), daemon=True)
|
|
133
|
+
proc.start()
|
|
134
|
+
child.close()
|
|
135
|
+
self._proc, self._conn = proc, parent
|
|
136
|
+
try:
|
|
137
|
+
ready = parent.poll(STARTUP_SECONDS) and parent.recv() == "ready"
|
|
138
|
+
except (EOFError, OSError):
|
|
139
|
+
ready = False
|
|
140
|
+
if not ready:
|
|
141
|
+
self.close()
|
|
142
|
+
raise RuntimeError("the extraction worker process did not start")
|
|
143
|
+
|
|
144
|
+
def run(self, kind: str, expr: str, text: str) -> list[str] | None:
|
|
145
|
+
"""Values, or None when the budget ran out (the worker is then restarted)."""
|
|
146
|
+
if self._proc is None or not self._proc.is_alive():
|
|
147
|
+
self._start()
|
|
148
|
+
try:
|
|
149
|
+
self._conn.send((kind, expr, text[:MAX_INPUT]))
|
|
150
|
+
if self._conn.poll(self.budget):
|
|
151
|
+
return [clean(v, 500) for v in self._conn.recv()][:MAX_VALUES
|
|
152
|
+
if kind != "regex"
|
|
153
|
+
else MAX_REGEX_MATCHES]
|
|
154
|
+
except (EOFError, OSError):
|
|
155
|
+
pass
|
|
156
|
+
self.close()
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
def findall(self, pattern: str, text: str) -> list[str] | None:
|
|
160
|
+
return self.run("regex", pattern, text)
|
|
161
|
+
|
|
162
|
+
def close(self) -> None:
|
|
163
|
+
if self._conn is not None:
|
|
164
|
+
try:
|
|
165
|
+
self._conn.close()
|
|
166
|
+
except OSError:
|
|
167
|
+
pass
|
|
168
|
+
if self._proc is not None:
|
|
169
|
+
if self._proc.is_alive():
|
|
170
|
+
self._proc.kill()
|
|
171
|
+
self._proc.join(5)
|
|
172
|
+
self._proc = self._conn = None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
RegexRunner = ExtractRunner # the name used by earlier tests
|