Feature: crawl analysis, indexability, link metrics, sitemap audit, crawl comparison

Site-wide crawl analysis that runs once when a crawl finishes, linear in
URLs + links:
- Indexability column (Indexable / Non-Indexable + reason), reading the
  X-Robots-Tag header as well as the robots meta tag
- Duplicate title, meta description and H1 across indexable pages;
  multiple title / meta description / H1 tags per page
- Redirect chains, loops and redirects to broken URLs, followed or not
- Unique inlinks/outlinks and Link Score (internal PageRank, 0-100)
- Per-page broken internal/external links and links to redirects
- Canonicals pointing at non-indexable URLs, canonical chains, multiple and
  conflicting canonicals (HTML tags and Link headers)
- Sitemap audit: orphan pages, non-indexable URLs in the sitemap, indexable
  pages missing from it

Crawl comparison tab and /api/crawls/compare (JSON or CSV): new/removed
URLs, status, indexability, title, meta, H1, canonical and word-count
changes, and issues that appeared or were resolved.

Hardening found by fuzzing: a malformed href, Location or sitemap <loc> no
longer loses a page or the rest of the sitemap; UTF-8 headers decode
correctly; a corrupt DB value can no longer empty a loaded crawl. Resumed
crawls no longer save end-of-crawl issues twice, and linked_from is saved
complete.
This commit is contained in:
phialsbasement committed 2026-11-07 13:06:50 +11:00
1 parent b5b288f489
commit f25bee606c
16 files changed
+2410 -50

No files matched your search

+99
View File
@@ -1165,6 +1165,10 @@ def filter_crawl_urls(urls, filter_type):
keep = 'javascript' in content_type
elif filter_type == 'images':
keep = 'image' in content_type
elif filter_type == 'indexable':
keep = u.get('indexability') == 'Indexable'
elif filter_type == 'non_indexable':
keep = u.get('indexability') == 'Non-Indexable'
else:
keep = True
if keep:
@@ -1539,6 +1543,101 @@ def crawl_stats():
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
COMPARE_MAX_ROWS = 50000
def _can_access_crawl(crawl):
"""Owners see their crawls; a guest only the crawls of its own session."""
if not crawl:
return False
user_id = session.get('user_id')
if user_id:
return crawl.get('user_id') == user_id
return crawl.get('session_id') == session.get('session_id')
@app.route('/api/crawls/compare')
@login_required
def compare_crawls_endpoint():
"""Diff two saved crawls: ?previous=<id>&current=<id>.
current defaults to the crawl loaded in this session. format=csv streams
every change; JSON returns the summary plus up to COMPARE_MAX_ROWS rows.
"""
from flask import Response
from src.crawl_db import get_crawl_by_id, load_compare_rows, load_issue_names
from src.core.crawl_compare import compare_crawls, CHANGE_KINDS
try:
previous_id = request.args.get('previous', type=int)
current_id = request.args.get('current', type=int)
if current_id is None:
current_id = get_or_create_crawler().crawl_id
if not previous_id or not current_id:
return jsonify({'success': False,
'error': 'Pick a saved crawl to compare against the current one'}), 400
if previous_id == current_id:
return jsonify({'success': False, 'error': 'Pick two different crawls'}), 400
previous, current = get_crawl_by_id(previous_id), get_crawl_by_id(current_id)
if not previous or not current:
return jsonify({'success': False, 'error': 'Crawl not found'}), 404
if not _can_access_crawl(previous) or not _can_access_crawl(current):
return jsonify({'success': False, 'error': 'Unauthorized'}), 403
# Issues hidden by the exclusion patterns stay hidden here too
exclusion_patterns = get_exclusion_patterns(get_session_settings())
def issues_for(crawl_id):
issues = load_issue_names(crawl_id)
if not exclusion_patterns:
return issues
return [i for i in issues
if not issue_matches_exclusion({'url': i[0]}, exclusion_patterns)]
diff = compare_crawls(load_compare_rows(previous_id), load_compare_rows(current_id),
issues_for(previous_id), issues_for(current_id))
def describe(crawl):
return {'id': crawl['id'], 'base_url': crawl.get('base_url'),
'started_at': crawl.get('started_at'), 'status': crawl.get('status'),
'urls_crawled': crawl.get('urls_crawled')}
if request.args.get('format') == 'csv':
labels = dict(CHANGE_KINDS)
def generate():
out = StringIO()
writer = csv.writer(out)
writer.writerow(['url', 'change', 'previous', 'current'])
for change in diff['changes']:
writer.writerow([change['url'], labels.get(change['change'], change['change']),
change['previous'], change['current']])
if out.tell() > 65536:
yield out.getvalue()
out.seek(0)
out.truncate()
yield out.getvalue()
filename = f'librecrawl_compare_{previous_id}_vs_{current_id}.csv'
return Response(generate(), mimetype='text/csv',
headers={'Content-Disposition': f'attachment; filename={filename}'})
changes = diff['changes']
return jsonify({
'success': True,
'previous': describe(previous),
'current': describe(current),
'summary': diff['summary'],
'issue_changes': diff['issue_changes'],
'change_kinds': [{'key': k, 'label': label} for k, label in CHANGE_KINDS],
'changes': changes[:COMPARE_MAX_ROWS],
'truncated': len(changes) > COMPARE_MAX_ROWS,
'total_changes': len(changes),
})
except Exception as e:
import traceback
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/export_stream')
@login_required
def export_stream():
+590
View File
@@ -0,0 +1,590 @@
"""Site-wide crawl analysis.
Most checks look at one page at a time and run as each page is crawled. The
ones here need the whole crawl (who links to a page, which other pages share
its title, whether its canonical target is itself indexable), so they run
once when the crawl finishes, like Screaming Frog's "Crawl Analysis".
Everything is a single pass over the rows and a single pass over the links,
with dict lookups, so the cost grows linearly with the crawl. The one
iterative step, Link Score (internal PageRank), runs at most
LINK_SCORE_ITERATIONS rounds over the link graph and stops early on
convergence or after LINK_SCORE_TIME_BUDGET_SECONDS.
"""
import math
import time
from collections import defaultdict
from urllib.parse import urljoin
from .link_manager import normalize_url
INDEXABLE = 'Indexable'
NON_INDEXABLE = 'Non-Indexable'
LINK_SCORE_DAMPING = 0.85
LINK_SCORE_ITERATIONS = 40
LINK_SCORE_TIME_BUDGET_SECONDS = 30
MAX_REDIRECT_HOPS = 10
EXAMPLES_PER_ISSUE = 3
# Issues produced by the site-wide pass. A resumed crawl recomputes them at
# the end, so these are dropped when a crawl is resumed rather than repeated.
ANALYSIS_ISSUES = frozenset({
'Duplicate Title',
'Duplicate Meta Description',
'Duplicate H1',
'Broken Internal Links',
'Broken External Links',
'Internal Links to Redirects',
'Redirect Chain',
'Redirect Loop',
'Redirect to Broken URL',
'Canonical Points to Non-Indexable URL',
'Canonical Chain',
'Orphan Page (Sitemap Only)',
'Non-Indexable URL in Sitemap',
'Indexable Page Not in Sitemap',
})
# Fields the analysis writes onto each row
ANALYSIS_FIELDS = ('indexability', 'indexability_status', 'inlinks', 'outlinks',
'link_score', 'in_sitemap')
def _safe_normalize(url, base=None):
"""normalize_url(urljoin(base, url)), or '' for anything unparseable
(a malformed href or header must never abort the whole analysis)."""
if not url or not isinstance(url, str):
return ''
try:
return normalize_url(urljoin(base, url) if base else url)
except (ValueError, TypeError):
return ''
def is_html(row):
return 'html' in (row.get('content_type') or '').lower()
def final_url(row):
"""Where the row's content actually lives after any redirects."""
return row.get('redirected_to') or row.get('url', '')
def _resolve_canonical(row, href):
if not isinstance(href, str):
return ''
target = _safe_normalize(href.strip(), final_url(row))
# A javascript:/mailto:/data: "canonical" names no page; treat it as
# absent rather than as pointing the page somewhere else
return target if target.startswith(('http://', 'https://')) else ''
def canonical_targets(row):
"""Distinct pages the row's canonical declarations (HTML tags and Link
headers) point at, normalised, in declaration order."""
declared = row.get('canonicals') or [row.get('canonical_url')]
targets = []
for href in declared:
target = _resolve_canonical(row, href)
if target and target not in targets:
targets.append(target)
return targets
def has_conflicting_canonicals(row):
return (row.get('canonical_count') or 0) > 1 and len(canonical_targets(row)) > 1
def canonical_target(row):
"""The row's canonical as a normalised absolute URL, or ''.
Conflicting canonicals give '': search engines ignore every canonical
on a page whose declarations disagree.
"""
if (row.get('canonical_count') or 0) > 1:
# Several declarations: usable only when they agree (junk ones,
# e.g. an empty href, are ignored rather than counted as dissent)
targets = canonical_targets(row)
return targets[0] if len(targets) == 1 else ''
return _resolve_canonical(row, row.get('canonical_url'))
def is_canonicalised(row):
"""True when the canonical points at a different URL than the page."""
target = canonical_target(row)
if not target:
return False
here = _safe_normalize(final_url(row))
return bool(here) and target != here
def _robots_tokens(value):
"""Directives in a robots meta or X-Robots-Tag value.
X-Robots-Tag may name a crawler ("googlebot: noindex") and several headers
arrive joined with commas, so split on both and drop the crawler prefix.
"""
tokens = set()
for part in (value or '').lower().replace(';', ',').split(','):
part = part.strip()
if ':' in part:
part = part.split(':', 1)[1].strip()
if part:
tokens.add(part)
return tokens
def noindex_source(row):
"""'meta', 'header', or '' depending on where a noindex came from."""
meta = _robots_tokens(row.get('robots'))
if 'noindex' in meta or 'none' in meta:
return 'meta'
header = _robots_tokens(row.get('x_robots_tag'))
if 'noindex' in header or 'none' in header:
return 'header'
return ''
def nofollow_source(row):
meta = _robots_tokens(row.get('robots'))
if 'nofollow' in meta or 'none' in meta:
return 'meta'
header = _robots_tokens(row.get('x_robots_tag'))
if 'nofollow' in header or 'none' in header:
return 'header'
return ''
def indexability(row):
"""(Indexable | Non-Indexable, reason) for one crawled row.
Reasons, in the order they are checked: No Response, Blocked by
robots.txt, Redirected, Client Error, Server Error, noindex,
Canonicalised. The first that applies wins, so a 404 with a noindex
reads "Client Error".
"""
status = row.get('status_code') or 0
if row.get('error_type') == 'blocked_by_robots':
return NON_INDEXABLE, 'Blocked by robots.txt'
if status == 0:
return NON_INDEXABLE, 'No Response'
if row.get('redirects') or 300 <= status < 400:
return NON_INDEXABLE, 'Redirected'
if 400 <= status < 500:
return NON_INDEXABLE, 'Client Error'
if status >= 500:
return NON_INDEXABLE, 'Server Error'
if status != 200:
# 204 No Content, 206 etc.: nothing a search engine would index
return NON_INDEXABLE, f'Non-200 Status ({status})'
source = noindex_source(row)
if source == 'header':
return NON_INDEXABLE, 'noindex (X-Robots-Tag)'
if source:
return NON_INDEXABLE, 'noindex'
if is_html(row) and is_canonicalised(row):
return NON_INDEXABLE, 'Canonicalised'
return INDEXABLE, ''
def apply_indexability(row):
"""Set the indexability fields on a row (cheap; used while crawling)."""
label, reason = indexability(row)
row['indexability'] = label
row['indexability_status'] = reason
return row
def _is_broken(status):
return status is not None and (status == 0 or status >= 400)
def _examples(urls, exclude=None):
"""The first few of `urls` (skipping `exclude`, which callers pass only
when it is in the list) and how many more there are.
Stops scanning after EXAMPLES_PER_ISSUE: it runs once per page of a
duplicate group, so walking the whole group each time would make a
group of 20,000 identical meta descriptions quadratic.
"""
shown = []
for url in urls:
if url != exclude:
shown.append(url)
if len(shown) == EXAMPLES_PER_ISSUE:
break
total = len(urls) - (1 if exclude is not None else 0)
more = total - len(shown)
return ', '.join(shown) + (f' (+{more} more)' if more > 0 else '')
def _normalise_text(value):
if isinstance(value, list):
value = next((v for v in value if isinstance(v, str) and v.strip()), '')
if not isinstance(value, str):
return ''
return ' '.join(value.lower().split())
class CrawlAnalyzer:
"""Runs the site-wide checks over a finished crawl.
analyze() returns (patches, issues): patches maps each row's URL to the
analysis fields that changed, and issues are new issue dicts. Rows are
updated in place as well, so callers only journal the patches.
"""
def __init__(self, should_exclude=None):
self.should_exclude = should_exclude or (lambda url: False)
self.link_score_truncated = False
def analyze(self, rows, links, sitemap_urls=None, start_url=None):
started = time.monotonic()
rows = [r for r in rows if r.get('url') and not r.get('link_check_only')]
by_url = {r['url']: r for r in rows}
# Redirected rows are also reachable by their destination, so a
# canonical naming the destination still finds the crawled content
by_final = dict(by_url)
for r in rows:
dest = r.get('redirected_to')
if dest:
try:
by_final.setdefault(normalize_url(dest), r)
except ValueError:
pass
before = {r['url']: tuple(r.get(f) for f in ANALYSIS_FIELDS) for r in rows}
issues = []
for r in rows:
apply_indexability(r)
inlinks, outlinks = self._link_counts(rows, by_url, links, issues)
for r in rows:
if r.get('is_internal'):
r['inlinks'] = inlinks.get(r['url'], 0)
r['outlinks'] = outlinks.get(r['url'], 0)
self._link_score(rows, by_url, links, started)
self._duplicates(rows, issues)
self._redirect_graph(rows, by_url, issues)
self._canonicals(rows, by_final, issues)
self._sitemap(rows, sitemap_urls, start_url, issues)
patches = {}
for r in rows:
after = tuple(r.get(f) for f in ANALYSIS_FIELDS)
if after != before[r['url']]:
patches[r['url']] = {f: r.get(f) for f in ANALYSIS_FIELDS}
issues = [i for i in issues if not self.should_exclude(i['url'])]
return patches, issues
# ------------------------------------------------------------------
# Links: inlinks/outlinks plus the per-page broken/redirect link report
# ------------------------------------------------------------------
def _link_counts(self, rows, by_url, links, issues):
inlinks = defaultdict(int)
outlinks = defaultdict(int)
broken_internal = defaultdict(list)
broken_external = defaultdict(list)
to_redirects = defaultdict(list)
for link in links:
if link.get('placement') == 'image':
continue
source = link.get('source_url')
target = link.get('target_url')
if not source or not target or source == target:
continue
source_row = by_url.get(source)
# A redirecting URL's row holds its destination's HTML; those
# links belong to the destination, not to the redirect
if source_row is None or source_row.get('redirects'):
continue
target_row = by_url.get(target)
if link.get('is_internal'):
# (links are stored once per source/target pair, so these
# are unique inlinks, as Screaming Frog's "Unique Inlinks")
inlinks[target] += 1
outlinks[source] += 1
if target_row is not None:
status = target_row.get('status_code')
if target_row.get('error_type') == 'blocked_by_robots':
continue
if _is_broken(status):
broken_internal[source].append(f'{target} ({status or "no response"})')
elif target_row.get('redirects') or (status and 300 <= status < 400):
to_redirects[source].append(target)
elif _is_broken(link.get('target_status')):
broken_internal[source].append(
f'{target} ({link.get("target_status") or "no response"})')
elif _is_broken(link.get('target_status')):
status = link.get('target_status')
broken_external[source].append(f'{target} ({status or "no response"})')
for source, targets in broken_internal.items():
issues.append({
'url': source, 'type': 'error', 'category': 'Links',
'issue': 'Broken Internal Links',
'details': f"{len(targets)} link{'s' if len(targets) != 1 else ''} "
f"to broken internal URLs: {_examples(targets)}"
})
for source, targets in broken_external.items():
issues.append({
'url': source, 'type': 'warning', 'category': 'Links',
'issue': 'Broken External Links',
'details': f"{len(targets)} link{'s' if len(targets) != 1 else ''} "
f"to broken external URLs: {_examples(targets)}"
})
for source, targets in to_redirects.items():
issues.append({
'url': source, 'type': 'warning', 'category': 'Links',
'issue': 'Internal Links to Redirects',
'details': f"{len(targets)} link{'s' if len(targets) != 1 else ''} "
f"to redirecting URLs (link to the destination instead): "
f"{_examples(targets)}"
})
return inlinks, outlinks
# ------------------------------------------------------------------
# Link Score: PageRank over the internal link graph, scaled to 0-100
# ------------------------------------------------------------------
def _link_score(self, rows, by_url, links, started):
self.link_score_truncated = False
nodes = [r for r in rows if r.get('is_internal')]
count = len(nodes)
if count == 0:
return
index = {r['url']: i for i, r in enumerate(nodes)}
# Redirect rows pass nothing on through links (see _link_counts)
redirecting = {i for i, r in enumerate(nodes) if r.get('redirects')}
# Links are unique per source/target pair already (the link
# manager dedupes them), so no edge set is needed here
incoming = [[] for _ in range(count)]
outdegree = [0] * count
for link in links:
if not link.get('is_internal') or link.get('placement') == 'image':
continue
s = index.get(link.get('source_url'))
d = index.get(link.get('target_url'))
if s is None or d is None or s == d or s in redirecting:
continue
incoming[d].append(s)
outdegree[s] += 1
rank = [1.0 / count] * count
teleport = (1.0 - LINK_SCORE_DAMPING) / count
dangling = [i for i in range(count) if outdegree[i] == 0]
for _ in range(LINK_SCORE_ITERATIONS):
if time.monotonic() - started > LINK_SCORE_TIME_BUDGET_SECONDS:
self.link_score_truncated = True
print('Link Score stopped at its time budget; scores are approximate')
break
share = [rank[i] * LINK_SCORE_DAMPING / outdegree[i] if outdegree[i] else 0.0
for i in range(count)]
dangling_share = LINK_SCORE_DAMPING * sum(rank[i] for i in dangling) / count
base = teleport + dangling_share
new_rank = [base + sum(map(share.__getitem__, srcs)) if srcs else base
for srcs in incoming]
delta = sum(abs(a - b) for a, b in zip(new_rank, rank))
rank = new_rank
if delta < 1e-9 * count:
break
# Log scale, so the homepage reads 100 and deep pages are told apart
low, high = min(rank), max(rank)
# Ranks equal up to float noise (a cycle, a fully interlinked site)
# must score equally; scaling last-bit differences onto 0-100
# would invent a spread that is not there
if high <= low * (1 + 1e-6):
has_links = any(outdegree)
for r in nodes:
r['link_score'] = 100 if (has_links or count == 1) else 0
return
span = math.log(high / low)
for r, value in zip(nodes, rank):
score = round(100 * math.log(value / low) / span)
# Values within the noise band of the minimum read as 0
r['link_score'] = max(0, min(100, score))
# ------------------------------------------------------------------
# Duplicate titles, meta descriptions and H1s across indexable pages
# ------------------------------------------------------------------
def _duplicates(self, rows, issues):
pages = [r for r in rows
if r.get('is_internal') and is_html(r)
and r.get('indexability') == INDEXABLE]
for field, issue_name, label in (
('title', 'Duplicate Title', 'title'),
('meta_description', 'Duplicate Meta Description', 'meta description'),
('h1', 'Duplicate H1', 'H1')):
groups = defaultdict(list)
for r in pages:
value = _normalise_text(r.get(field))
if value:
groups[value].append(r['url'])
for urls in groups.values():
if len(urls) < 2:
continue
others = len(urls) - 1
for url in urls:
issues.append({
'url': url, 'type': 'warning', 'category': 'Duplication',
'issue': issue_name,
'details': f"Same {label} as {others} other indexable "
f"page{'s' if others != 1 else ''}: {_examples(urls, url)}"
})
# ------------------------------------------------------------------
# Redirect chains, loops and redirects that end in an error
# ------------------------------------------------------------------
def _redirect_graph(self, rows, by_url, issues):
# Followed redirects: the fetch recorded every hop itself
for r in rows:
if r.get('error_type') == 'redirect_loop':
issues.append({
'url': r['url'], 'type': 'error', 'category': 'Redirects',
'issue': 'Redirect Loop',
'details': r.get('error') or 'Too many redirects (redirect loop)'
})
continue
history = r.get('redirects') or []
if not history:
continue
path = [str((h or {}).get('url') or '?') for h in history] + [r.get('redirected_to') or '?']
status = r.get('status_code')
if len(history) >= 2:
issues.append({
'url': r['url'], 'type': 'warning', 'category': 'Redirects',
'issue': 'Redirect Chain',
'details': f'{len(history)} hops: ' + ' → '.join(path)
+ (f' ({status})' if status else '')
})
if _is_broken(status):
issues.append({
'url': r['url'], 'type': 'error', 'category': 'Redirects',
'issue': 'Redirect to Broken URL',
'details': f'Redirects to {path[-1]}, which returned {status or "no response"}'
})
# Redirects not followed: walk 3xx rows through their Location
hops = {}
for r in rows:
status = r.get('status_code') or 0
target = r.get('redirect_target')
if 300 <= status < 400 and target:
try:
hops[r['url']] = normalize_url(urljoin(r['url'], target))
except ValueError:
pass
for start in hops:
path = [start]
seen = {start}
current = start
loop = False
while current in hops and len(path) <= MAX_REDIRECT_HOPS:
current = hops[current]
if current in seen:
loop = True
path.append(current)
break
seen.add(current)
path.append(current)
if loop:
issues.append({
'url': start, 'type': 'error', 'category': 'Redirects',
'issue': 'Redirect Loop',
'details': 'Redirects back on itself: ' + ' → '.join(path)
})
else:
final_row = by_url.get(path[-1])
final_status = final_row.get('status_code') if final_row else None
if len(path) > 2:
issues.append({
'url': start, 'type': 'warning', 'category': 'Redirects',
'issue': 'Redirect Chain',
'details': f'{len(path) - 1} hops: ' + ' → '.join(path)
+ (f' ({final_status})' if final_status else '')
})
if final_row is not None and _is_broken(final_status):
issues.append({
'url': start, 'type': 'error', 'category': 'Redirects',
'issue': 'Redirect to Broken URL',
'details': f'Redirects to {path[-1]}, which returned '
f'{final_status or "no response"}'
})
# ------------------------------------------------------------------
# Canonicals pointing at non-indexable pages, or at another canonical
# ------------------------------------------------------------------
def _canonicals(self, rows, by_final, issues):
for r in rows:
if not is_html(r) or not r.get('is_internal'):
continue
if r.get('indexability_status') != 'Canonicalised':
continue
target = canonical_target(r)
target_row = by_final.get(target)
if target_row is None or target_row is r:
continue
label, reason = target_row.get('indexability'), target_row.get('indexability_status')
if label == NON_INDEXABLE and reason == 'Canonicalised':
issues.append({
'url': r['url'], 'type': 'warning', 'category': 'Canonicals',
'issue': 'Canonical Chain',
'details': f'Canonical {target} is itself canonicalised to '
f'{canonical_target(target_row)}'
})
elif label == NON_INDEXABLE:
issues.append({
'url': r['url'], 'type': 'error', 'category': 'Canonicals',
'issue': 'Canonical Points to Non-Indexable URL',
'details': f'Canonical {target} is non-indexable ({reason})'
})
# ------------------------------------------------------------------
# Sitemap audit
# ------------------------------------------------------------------
def _sitemap(self, rows, sitemap_urls, start_url, issues):
if not sitemap_urls:
for r in rows:
r['in_sitemap'] = None
return
start = _safe_normalize(start_url) if start_url else None
for r in rows:
in_map = r['url'] in sitemap_urls
r['in_sitemap'] = in_map
if not r.get('is_internal'):
continue
label, reason = r.get('indexability'), r.get('indexability_status')
if in_map and label == NON_INDEXABLE:
issues.append({
'url': r['url'], 'type': 'warning', 'category': 'Sitemaps',
'issue': 'Non-Indexable URL in Sitemap',
'details': f'Listed in the XML sitemap but non-indexable ({reason}). '
f'Sitemaps should list only indexable canonical URLs.'
})
if not is_html(r) or label != INDEXABLE:
continue
if in_map and not r.get('inlinks') and r['url'] != start:
issues.append({
'url': r['url'], 'type': 'warning', 'category': 'Sitemaps',
'issue': 'Orphan Page (Sitemap Only)',
'details': 'In the XML sitemap but no crawled page links to it'
})
elif not in_map:
issues.append({
'url': r['url'], 'type': 'info', 'category': 'Sitemaps',
'issue': 'Indexable Page Not in Sitemap',
'details': 'Indexable page found by crawling that the XML sitemap does not list'
})
+153
View File
@@ -0,0 +1,153 @@
"""Compare two crawls of a site: what was added, removed, or changed.
Rows are matched by URL. The comparison reads only a handful of columns per
crawl (see crawl_db.load_compare_rows) and is one pass over each crawl with
dict lookups, so it is linear in the crawl size.
"""
from collections import Counter
# Change kinds, in the order the UI lists them
CHANGE_KINDS = (
('added', 'New URL'),
('removed', 'Removed URL'),
('status', 'Status code changed'),
('indexability', 'Indexability changed'),
('title', 'Title changed'),
('meta_description', 'Meta description changed'),
('h1', 'H1 changed'),
('canonical', 'Canonical changed'),
('word_count', 'Word count changed'),
('new_issue', 'New issue'),
('resolved_issue', 'Resolved issue'),
)
# A word-count change smaller than this share of the old count is noise
WORD_COUNT_CHANGE_RATIO = 0.2
_TEXT_FIELDS = (
('title', 'title'),
('meta_description', 'meta_description'),
('h1', 'h1'),
('canonical', 'canonical_url'),
)
def _clean(value):
if value is None:
return ''
return ' '.join(str(value).split())
def _index_label(row):
label = row.get('indexability') or ''
reason = row.get('indexability_status') or ''
return f'{label} ({reason})' if reason else label
def _status_label(row):
status = row.get('status_code')
if not status:
return row.get('error_type') or 'no response'
return str(status)
def compare_crawls(previous_rows, current_rows, previous_issues, current_issues):
"""Diff two crawls.
previous_rows/current_rows: dicts from load_compare_rows.
previous_issues/current_issues: (url, issue, type) tuples.
Returns {'summary': {...}, 'issue_changes': [...], 'changes': [...]},
where each change is {'url', 'change', 'previous', 'current'}.
"""
prev = {r['url']: r for r in previous_rows if r.get('url') and not r.get('link_check_only')}
cur = {r['url']: r for r in current_rows if r.get('url') and not r.get('link_check_only')}
# Issue rows come straight from SQLite, where the columns are nullable
previous_issues = [(url, str(issue), kind or '') for url, issue, kind in previous_issues
if url and issue]
current_issues = [(url, str(issue), kind or '') for url, issue, kind in current_issues
if url and issue]
changes = []
for url, row in cur.items():
old = prev.get(url)
if old is None:
changes.append({'url': url, 'change': 'added', 'previous': '',
'current': _status_label(row)})
continue
if (old.get('status_code') or 0) != (row.get('status_code') or 0):
changes.append({'url': url, 'change': 'status',
'previous': _status_label(old), 'current': _status_label(row)})
# Indexability is only compared when both crawls recorded it
# (crawls saved before it existed have none)
if old.get('indexability') and row.get('indexability'):
before, after = _index_label(old), _index_label(row)
if before != after:
changes.append({'url': url, 'change': 'indexability',
'previous': before, 'current': after})
for kind, field in _TEXT_FIELDS:
before, after = _clean(old.get(field)), _clean(row.get(field))
if before != after:
changes.append({'url': url, 'change': kind, 'previous': before, 'current': after})
before, after = old.get('word_count') or 0, row.get('word_count') or 0
if before != after and abs(after - before) >= max(1, before) * WORD_COUNT_CHANGE_RATIO:
changes.append({'url': url, 'change': 'word_count',
'previous': str(before), 'current': str(after)})
for url, row in prev.items():
if url not in cur:
changes.append({'url': url, 'change': 'removed',
'previous': _status_label(row), 'current': ''})
# Issues: per URL, which issue names appeared or went away. A URL that
# is only in one crawl is already reported as added/removed, so its
# issues are not listed again one by one.
prev_by_url, cur_by_url = {}, {}
for url, issue, _ in previous_issues:
prev_by_url.setdefault(url, set()).add(issue)
for url, issue, _ in current_issues:
cur_by_url.setdefault(url, set()).add(issue)
for url, names in cur_by_url.items():
if url not in prev:
continue
for name in sorted(names - prev_by_url.get(url, set())):
changes.append({'url': url, 'change': 'new_issue', 'previous': '', 'current': name})
for url, names in prev_by_url.items():
if url not in cur:
continue
for name in sorted(names - cur_by_url.get(url, set())):
changes.append({'url': url, 'change': 'resolved_issue', 'previous': name, 'current': ''})
# Totals per issue name, for the summary table
prev_counts = Counter(issue for _, issue, _ in previous_issues)
cur_counts = Counter(issue for _, issue, _ in current_issues)
issue_types = {}
for _, issue, kind in previous_issues:
issue_types[issue] = kind
for _, issue, kind in current_issues:
issue_types[issue] = kind
issue_changes = sorted(
({'issue': name, 'type': issue_types.get(name, ''),
'previous': prev_counts.get(name, 0), 'current': cur_counts.get(name, 0),
'delta': cur_counts.get(name, 0) - prev_counts.get(name, 0)}
for name in set(prev_counts) | set(cur_counts)),
key=lambda c: (-abs(c['delta']), c['issue']))
order = {kind: i for i, (kind, _) in enumerate(CHANGE_KINDS)}
changes.sort(key=lambda c: (order.get(c['change'], 99), c['url']))
by_kind = Counter(c['change'] for c in changes)
summary = {
'previous_urls': len(prev),
'current_urls': len(cur),
'previous_issues': len(previous_issues),
'current_issues': len(current_issues),
'changes': {kind: by_kind.get(kind, 0) for kind, _ in CHANGE_KINDS},
}
return {'summary': summary, 'issue_changes': issue_changes, 'changes': changes}
+73 -11
View File
@@ -7,6 +7,9 @@ from collections import defaultdict
from fnmatch import fnmatch
from urllib.parse import urlparse
from .crawl_analysis import (canonical_target, canonical_targets, is_canonicalised,
noindex_source, nofollow_source)
# Near-duplicate detection is bounded so a large site can never hold a crawl in
# "finishing up" indefinitely: when the budget is exhausted the pass stops with
# a warning and partial results instead of running to completion.
@@ -102,6 +105,16 @@ class IssueDetector:
'details': f"Title is {len(title)} characters (recommended: 30-60)"
})
if (result.get('title_count') or 0) > 1:
issues.append({
'url': url,
'type': 'warning',
'category': 'SEO',
'issue': 'Multiple Title Tags',
'details': f"Page has {result['title_count']} <title> tags in <head>; "
f"search engines may pick either"
})
def _check_meta_description_issues(self, result, issues):
"""Check for meta description issues"""
url = result.get('url', '')
@@ -132,6 +145,15 @@ class IssueDetector:
'details': f"Description is {len(meta_desc)} characters (recommended: 120-160)"
})
if (result.get('meta_description_count') or 0) > 1:
issues.append({
'url': url,
'type': 'warning',
'category': 'SEO',
'issue': 'Multiple Meta Descriptions',
'details': f"Page has {result['meta_description_count']} meta description tags"
})
def _check_heading_issues(self, result, issues):
"""Check for heading-related issues"""
url = result.get('url', '')
@@ -144,11 +166,19 @@ class IssueDetector:
'issue': 'Missing H1 Tag',
'details': 'Page has no H1 heading'
})
elif (result.get('h1_count') or 0) > 1:
issues.append({
'url': url,
'type': 'warning',
'category': 'SEO',
'issue': 'Multiple H1 Tags',
'details': f"Page has {result['h1_count']} H1 headings (recommended: one)"
})
def _check_content_issues(self, result, issues):
"""Check for content-related issues"""
url = result.get('url', '')
word_count = result.get('word_count', 0)
word_count = result.get('word_count') or 0
if word_count < 300:
issues.append({
@@ -162,7 +192,7 @@ class IssueDetector:
def _check_technical_issues(self, result, issues):
"""Check for technical SEO issues"""
url = result.get('url', '')
status_code = result.get('status_code', 0)
status_code = result.get('status_code') or 0
# No HTTP response at all (DNS failure, connection refused, timeout, etc.)
if status_code == 0:
@@ -226,15 +256,42 @@ class IssueDetector:
'issue': 'Missing Canonical URL',
'details': 'Page has no canonical URL specified'
})
elif canonical_url != url:
elif is_canonicalised(result):
# Compared after resolving and normalising, so a relative
# canonical naming the page itself is not "different"
issues.append({
'url': url,
'type': 'warning',
'category': 'Technical',
'issue': 'Canonical URL Different',
'details': f"Canonical points to: {canonical_url}"
'details': f"Canonical points to: {canonical_target(result)}"
})
# Several canonical declarations (HTML tags and/or Link headers)
count = result.get('canonical_count') or 0
if count > 1:
targets = canonical_targets(result)
sources = 'tags' if not result.get('canonical_header') else 'tags/headers'
if len(targets) > 1:
shown = ', '.join(targets[:3]) + (f' (+{len(targets) - 3} more)' if len(targets) > 3 else '')
issues.append({
'url': url,
'type': 'error',
'category': 'Technical',
'issue': 'Conflicting Canonicals',
'details': f"{count} canonical {sources} name {len(targets)} different URLs, "
f"so search engines ignore all of them: {shown}"
})
else:
issues.append({
'url': url,
'type': 'info',
'category': 'Technical',
'issue': 'Multiple Canonical Tags',
'details': f"{count} canonical {sources}, all naming "
f"{targets[0] if targets else 'no valid URL'}; one is enough"
})
def _check_mobile_issues(self, result, issues):
"""Check for mobile optimization issues"""
url = result.get('url', '')
@@ -361,24 +418,27 @@ class IssueDetector:
def _check_indexability_issues(self, result, issues):
"""Check for indexability issues"""
url = result.get('url', '')
robots = result.get('robots', '').lower()
where = {'meta': 'robots meta tag', 'header': 'X-Robots-Tag HTTP header'}
if 'noindex' in robots:
source = noindex_source(result)
if source:
issues.append({
'url': url,
'type': 'error',
'category': 'Indexability',
'issue': 'Noindex Tag Present',
'details': 'Page is BLOCKED from search engines - has noindex directive'
'details': f'Page is BLOCKED from search engines - noindex in the {where[source]}'
})
if 'nofollow' in robots:
source = nofollow_source(result)
if source:
issues.append({
'url': url,
'type': 'error',
'category': 'Indexability',
'issue': 'Nofollow Tag Present',
'details': 'Links on this page are NOT followed by search engines - has nofollow directive'
'details': f'Links on this page are NOT followed by search engines - '
f'nofollow in the {where[source]}'
})
def _check_broken_image_issues(self, result, issues):
@@ -630,8 +690,10 @@ class IssueDetector:
def _should_exclude(self, url):
"""Check if URL should be excluded from issue detection"""
parsed = urlparse(url)
path = parsed.path
try:
path = urlparse(url or '').path
except ValueError:
return False # unparseable (e.g. a broken IPv6 host): nothing to match
for pattern in self.exclusion_patterns:
if '*' in pattern:
+24 -1
View File
@@ -108,6 +108,23 @@ class JavaScriptRenderer:
pass
return navigation_ms
@staticmethod
async def _redirect_chain(response):
"""HTTP redirect hops before the final response, oldest first, in the
same shape the requests path records: [{'url', 'status_code'}]."""
hops = []
try:
request = response.request.redirected_from if response else None
while request is not None and len(hops) < 30:
hop_response = await request.response()
hops.append({'url': request.url,
'status_code': hop_response.status if hop_response else None})
request = request.redirected_from
except Exception:
return []
hops.reverse()
return hops
async def render_page(self, url):
"""
Render a page with JavaScript and return the HTML content
@@ -146,8 +163,14 @@ class JavaScriptRenderer:
status_code = response.status if response else 200
render_ms = (time.monotonic() - started) * 1000
# Besides timings, carry the response details the crawler
# needs for indexability: X-Robots-Tag and redirect hops
headers = response.headers if response else {}
return html_content, status_code, None, page.url, {
'response_ms': response_ms, 'render_ms': render_ms}
'response_ms': response_ms, 'render_ms': render_ms,
'x_robots_tag': headers.get('x-robots-tag', ''),
'link_header': headers.get('link', ''),
'redirects': await self._redirect_chain(response)}
except PlaywrightTimeoutError:
return None, 0, "JavaScript rendering timeout", None, empty_timing
+7 -5
View File
@@ -65,11 +65,13 @@ class LinkManager:
if not href or href.startswith('#') or href.startswith('mailto:') or href.startswith('tel:'):
continue
# Convert relative URLs to absolute
absolute_url = urljoin(resolve_base, href)
# Clean URL (remove fragment)
clean_url = normalize_url(absolute_url)
# Convert relative URLs to absolute and drop the fragment. One
# malformed href (e.g. "http://[bad/") is skipped; it must not
# take the rest of the page's links down with it.
try:
clean_url = normalize_url(urljoin(resolve_base, href))
except ValueError:
continue
# Thread-safe checking and adding
with self.urls_lock:
+61 -18
View File
@@ -6,6 +6,30 @@ from urllib.parse import urljoin, urlparse
from .ngram_analyzer import visible_text, heading_texts
# Content inside these belongs to an embedded document or graphic, not to
# the page: an <svg> or <object> carries its own <title>. (html.parser keeps
# <iframe> content as raw text already, and <embed> is void, but both are
# listed so a parser change cannot start counting them.)
EMBEDDED_CONTAINERS = frozenset({'svg', 'iframe', 'embed', 'object'})
# Most canonical declarations kept per page (HTML tags plus Link headers)
MAX_CANONICALS = 10
def is_embedded(tag):
"""True when the tag sits inside an embedded document or graphic."""
return any(parent.name in EMBEDDED_CONTAINERS for parent in tag.parents)
def rel_tokens(tag):
"""A link's rel attribute as lower-cased tokens (rel is multi-valued:
rel="alternate canonical", and HTML is case-insensitive)."""
rel = tag.get('rel') or []
if isinstance(rel, str):
rel = rel.split()
return {token.lower() for token in rel}
class SEOExtractor:
"""Extracts SEO-related data from HTML content"""
@@ -13,16 +37,21 @@ class SEOExtractor:
def extract_basic_seo_data(soup, result):
"""Extract basic SEO data (title, headings, meta description, etc.)"""
# Extract title
title_tag = soup.find('title')
result['title'] = title_tag.get_text().strip() if title_tag else ''
# Every <title> in the document counts (a second <head>, or one
# stray in the body, is still a title search engines see) except
# those of embedded graphics/documents (SVG icons, <object>)
titles = [t for t in soup.find_all('title') if not is_embedded(t)]
result['title'] = titles[0].get_text().strip() if titles else ''
result['title_count'] = len(titles)
# Extract meta description
meta_desc = soup.find('meta', attrs={'name': 'description'})
result['meta_description'] = meta_desc.get('content', '').strip() if meta_desc else ''
# Extract headings
h1_tag = soup.find('h1')
result['h1'] = h1_tag.get_text().strip() if h1_tag else ''
# Extract headings (find_all walks the tree once, same as find)
h1_tags = soup.find_all('h1')
result['h1'] = h1_tags[0].get_text().strip() if h1_tags else ''
result['h1_count'] = len(h1_tags)
h2_tags = soup.find_all('h2')
result['h2'] = [h2.get_text().strip() for h2 in h2_tags[:10]]
@@ -58,6 +87,7 @@ class SEOExtractor:
def extract_meta_tags(soup, result):
"""Extract all meta tags"""
meta_tags = soup.find_all('meta')
description_count = 0
for meta in meta_tags:
name = meta.get('name', '').lower()
@@ -67,7 +97,9 @@ class SEOExtractor:
result['meta_tags'][name] = content
# Extract specific important meta tags
if name == 'viewport':
if name == 'description':
description_count += 1
elif name == 'viewport':
result['viewport'] = content
elif name == 'robots':
result['robots'] = content
@@ -80,9 +112,15 @@ class SEOExtractor:
elif name == 'theme-color':
result['theme_color'] = content
# Extract canonical URL
canonical = soup.find('link', attrs={'rel': 'canonical'})
result['canonical_url'] = canonical.get('href', '') if canonical else ''
result['meta_description_count'] = description_count
# Canonical declarations: all of them, so several (conflicting or
# not) can be reported. The first is the page's canonical.
hrefs = [(link.get('href') or '').strip() for link in soup.find_all('link')
if 'canonical' in rel_tokens(link) and not is_embedded(link)]
result['canonical_url'] = hrefs[0] if hrefs else ''
result['canonicals'] = hrefs[:MAX_CANONICALS]
result['canonical_count'] = len(hrefs)
@staticmethod
def extract_opengraph_tags(soup, result):
@@ -175,13 +213,16 @@ class SEOExtractor:
if src:
# Convert relative URLs to absolute
if src.startswith('//'):
src = 'https:' + src
elif src.startswith('/'):
parsed_base = urlparse(base_url)
src = f"{parsed_base.scheme}://{parsed_base.netloc}{src}"
elif not src.startswith(('http://', 'https://')):
src = urljoin(base_url, src)
try:
if src.startswith('//'):
src = 'https:' + src
elif src.startswith('/'):
parsed_base = urlparse(base_url)
src = f"{parsed_base.scheme}://{parsed_base.netloc}{src}"
elif not src.startswith(('http://', 'https://')):
src = urljoin(base_url, src)
except ValueError:
pass # malformed src: keep it as written
result['images'].append({
'src': src,
@@ -199,8 +240,10 @@ class SEOExtractor:
for link in links:
href = link.get('href', '')
if href and not href.startswith(('#', 'mailto:', 'tel:', 'javascript:')):
absolute_url = urljoin(result['url'], href)
parsed_url = urlparse(absolute_url)
try:
parsed_url = urlparse(urljoin(result['url'], href))
except ValueError:
continue # malformed href, e.g. "http://[bad/"
# Handle www vs non-www domains
url_domain_clean = parsed_url.netloc.replace('www.', '', 1)
+116 -3
View File
@@ -13,6 +13,36 @@ from contextlib import contextmanager
import os
DB_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'users.db')
# Row fields stored together in the crawled_urls.analysis JSON column rather
# than one column each: indexing directives, tag counts, redirect details and
# the end-of-crawl analysis (inlinks, Link Score, sitemap membership).
ANALYSIS_KEYS = (
'x_robots_tag', 'title_count', 'meta_description_count', 'h1_count',
'canonicals', 'canonical_count', 'canonical_header',
'redirected_to', 'redirect_target',
'indexability', 'indexability_status',
'inlinks', 'outlinks', 'link_score', 'in_sitemap',
)
def _load_analysis(text):
"""The analysis column as a dict of known keys. Anything unreadable
yields {} for that row: one bad value must not lose a whole crawl."""
if not text:
return {}
try:
value = json.loads(text)
except (ValueError, TypeError):
return {}
if not isinstance(value, dict):
return {}
return {k: value[k] for k in ANALYSIS_KEYS if k in value}
def _analysis_json(url_data):
values = {k: url_data[k] for k in ANALYSIS_KEYS if url_data.get(k) is not None}
return json.dumps(values) if values else None
@contextmanager
def get_db():
"""Context manager for database connections"""
@@ -154,6 +184,12 @@ def init_crawl_tables():
except sqlite3.OperationalError:
pass # Column already exists
# Migration: analysis, JSON of ANALYSIS_KEYS
try:
cursor.execute('ALTER TABLE crawled_urls ADD COLUMN analysis TEXT')
except sqlite3.OperationalError:
pass # Column already exists
# Migration: anchor_alt for image-only inlinks
try:
cursor.execute('ALTER TABLE crawl_links ADD COLUMN anchor_alt TEXT')
@@ -343,7 +379,8 @@ def save_url_batch(crawl_id, urls):
url_data.get('render_time'),
url_data.get('link_check_only', False),
(json.dumps(url_data['custom_extraction'])
if url_data.get('custom_extraction') is not None else None)
if url_data.get('custom_extraction') is not None else None),
_analysis_json(url_data)
)
rows.append(row)
@@ -356,8 +393,8 @@ def save_url_batch(crawl_id, urls):
meta_tags, og_tags, twitter_tags, json_ld, analytics, images,
hreflang, schema_org, redirects, linked_from,
external_links, internal_links, response_time, javascript_rendered,
error_type, render_time, link_check_only, custom_extraction
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
error_type, render_time, link_check_only, custom_extraction, analysis
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', rows)
print(f"Saved {len(urls)} URLs to database for crawl {crawl_id}")
@@ -441,6 +478,77 @@ def save_issues_batch(crawl_id, issues):
print(f"Error saving issues batch: {e}")
return False
def update_url_analysis(crawl_id, urls, chunk_size=5000):
"""Rewrite the analysis JSON and linked_from of rows already saved.
Called once when a crawl finishes. Uses the (crawl_id, url) index and
commits per chunk, so a large crawl never holds the write lock for long
while request handlers are reading.
"""
if not urls:
return True
try:
for start in range(0, len(urls), chunk_size):
chunk = urls[start:start + chunk_size]
rows = [(_analysis_json(u), json.dumps(u.get('linked_from', [])), crawl_id, u.get('url'))
for u in chunk if u.get('url')]
with get_db() as conn:
conn.executemany(
'UPDATE crawled_urls SET analysis = ?, linked_from = ? '
'WHERE crawl_id = ? AND url = ?', rows)
print(f"Saved crawl analysis for {len(urls)} URLs (crawl {crawl_id})")
return True
except Exception as e:
print(f"Error saving crawl analysis: {e}")
return False
def delete_issues_by_name(crawl_id, issue_names):
"""Delete a crawl's issues with the given names (recomputed ones)."""
names = list(issue_names)
if not names:
return True
try:
with get_db() as conn:
placeholders = ','.join('?' * len(names))
conn.execute(f'DELETE FROM crawl_issues WHERE crawl_id = ? AND issue IN ({placeholders})',
[crawl_id, *names])
return True
except Exception as e:
print(f"Error deleting issues: {e}")
return False
def load_compare_rows(crawl_id):
"""The columns crawl comparison needs, one dict per crawled URL.
Reads only these columns (never body text, JSON blobs or links), so
comparing two large crawls stays cheap.
"""
with get_db() as conn:
cursor = conn.execute('''
SELECT url, status_code, content_type, is_internal, title, meta_description,
h1, canonical_url, word_count, error_type, link_check_only, analysis
FROM crawled_urls WHERE crawl_id = ?
''', (crawl_id,))
rows = []
for row in cursor:
data = dict(row)
analysis = _load_analysis(data.pop('analysis', None))
data['indexability'] = analysis.get('indexability')
data['indexability_status'] = analysis.get('indexability_status')
rows.append(data)
return rows
def load_issue_names(crawl_id):
"""(url, issue, type) for every issue of a crawl."""
with get_db() as conn:
cursor = conn.execute('SELECT url, issue, type FROM crawl_issues WHERE crawl_id = ?',
(crawl_id,))
return [(r['url'], r['issue'], r['type']) for r in cursor]
def save_checkpoint(crawl_id, checkpoint_data):
"""Save queue checkpoint for crash recovery"""
try:
@@ -577,6 +685,11 @@ def load_crawled_urls(crawl_id, limit=None, offset=0):
except ValueError:
pass
# Analysis fields go back onto the row as plain keys
analysis = _load_analysis(url_data.pop('analysis', None))
if analysis:
url_data.update(analysis)
urls.append(url_data)
return urls
+226 -7
View File
@@ -22,6 +22,73 @@ IMAGE_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'avif', '
HEAD_CHECK_WORKERS = 5
class _CrawlSession(requests.Session):
"""requests.Session that treats an unfollowable Location as the end of
the redirect chain.
requests parses the next hop even with allow_redirects=False (it fills
response.next), so a Location such as "http://[bad/" or
"javascript:alert(1)" raised and the 3xx response was lost: the URL was
reported as a failed fetch. Stopping there keeps the 3xx as the result,
which is what it is: a redirect nobody can follow. Network errors on a
followable target and too-many-redirects still raise as before.
"""
_UNFOLLOWABLE = (ValueError, requests.exceptions.InvalidURL,
requests.exceptions.InvalidSchema, requests.exceptions.MissingSchema)
def resolve_redirects(self, resp, req, *args, **kwargs):
generator = super().resolve_redirects(resp, req, *args, **kwargs)
while True:
try:
yield next(generator)
except StopIteration:
return
except self._UNFOLLOWABLE:
return
def _header_text(value):
"""A response header as the server meant it. http.client decodes headers
as latin-1, but non-ASCII header bytes are nearly always UTF-8 (requests
applies the same repair to Location when it follows a redirect)."""
if not value:
return ''
try:
return value.encode('latin-1').decode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
return value
def _header_canonicals(link_header):
"""URLs a Link response header declares canonical, e.g.
Link: <https://example.com/page>; rel="canonical"."""
if not link_header:
return []
try:
# requests joins repeated headers with ", ", Playwright with "\n"
links = requests.utils.parse_header_links(
_header_text(link_header).replace('\n', ', '))
except Exception:
return []
return [link['url'].strip() for link in links
if link.get('url') and 'canonical' in str(link.get('rel', '')).lower().split()]
def _apply_header_canonicals(result, link_header):
"""Merge canonicals from the Link header into the row: they count
towards multiple/conflicting canonicals, and stand in for the HTML
tag when the page has none (PDFs can only declare one this way)."""
urls = _header_canonicals(link_header)
if not urls:
return
result['canonical_header'] = urls[0]
result['canonicals'] = ((result.get('canonicals') or []) + urls)[:MAX_CANONICALS]
result['canonical_count'] = (result.get('canonical_count') or 0) + len(urls)
if not result.get('canonical_url'):
result['canonical_url'] = urls[0]
def classify_fetch_error(exc_or_msg):
"""Classify a failed-fetch error into a coarse error_type.
@@ -30,13 +97,15 @@ def classify_fetch_error(exc_or_msg):
Falls back to message inspection.
Returns one of: 'dns_not_found', 'timeout', 'connection_refused',
'ssl_error', 'connection_error'.
'ssl_error', 'redirect_loop', 'connection_error'.
"""
if isinstance(exc_or_msg, BaseException):
seen = set()
cur = exc_or_msg
while cur is not None and id(cur) not in seen:
seen.add(id(cur))
if isinstance(cur, requests.exceptions.TooManyRedirects):
return 'redirect_loop'
if isinstance(cur, socket.gaierror):
return 'dns_not_found'
if isinstance(cur, ssl.SSLError) or isinstance(cur, requests.exceptions.SSLError):
@@ -48,6 +117,8 @@ def classify_fetch_error(exc_or_msg):
cur = getattr(cur, '__cause__', None) or getattr(cur, '__context__', None)
msg = str(exc_or_msg).lower()
if 'too many redirects' in msg or 'err_too_many_redirects' in msg or 'exceeded 30 redirects' in msg:
return 'redirect_loop'
dns_markers = (
'getaddrinfo failed',
'name or service not known',
@@ -80,10 +151,16 @@ from src.core.memory_monitor import MemoryMonitor
from src.core.memory_profiler import UserMemoryTracker
from src.core.event_log import CrawlEventLog
from src.core.custom_extractor import CustomExtractor
from src.core.crawl_analysis import CrawlAnalyzer, ANALYSIS_ISSUES, apply_indexability
from src.core.link_manager import normalize_url
from src.core.seo_extractor import MAX_CANONICALS
# Upper bound on URLs accepted for one list-mode crawl
MAX_LIST_URLS = 100000
# Issues produced once the crawl finishes; a resumed crawl recomputes them
RECOMPUTED_AT_FINISH = ANALYSIS_ISSUES | {'Duplicate Content Detected'}
class WebCrawler:
"""
@@ -93,7 +170,7 @@ class WebCrawler:
def __init__(self, crawl_id=None, resume_from_db=False):
# HTTP session
self.session = requests.Session()
self.session = _CrawlSession()
self.session.headers.update({
'User-Agent': 'LibreCrawl/1.0 (Web Crawler)'
})
@@ -102,6 +179,7 @@ class WebCrawler:
# Base URL tracking
self.base_url = None
self.base_domain = None
self.start_url = None # the seed; never reported as an orphan
# Component instances (initialized on demand)
self.rate_limiter = None
@@ -160,6 +238,11 @@ class WebCrawler:
self._robots_locks = {}
self._robots_locks_guard = threading.Lock()
# Every URL listed in the site's XML sitemaps (normalised), for the
# sitemap audit. Filled by background discovery; empty when no
# sitemap was found or discovery is off.
self.sitemap_urls = set()
# HEAD status cache (avoids re-checking the same URL across pages)
self._head_status_cache = {}
# URLs already given a synthesized result row from a HEAD check
@@ -354,6 +437,7 @@ class WebCrawler:
parsed = urlparse(url)
self.base_url = f"{parsed.scheme}://{parsed.netloc}"
self.base_domain = parsed.netloc
self.start_url = normalize_url(url)
# Create database crawl record if session_id provided
if session_id:
@@ -436,6 +520,7 @@ class WebCrawler:
self.event_log.new_epoch()
self._head_status_cache.clear()
self._synthesized_urls.clear()
self.sitemap_urls = set()
self.stats = {
'discovered': 0,
'crawled': 0,
@@ -466,12 +551,29 @@ class WebCrawler:
"""Discover sitemaps and add URLs to crawl queue"""
sitemap_urls = self.sitemap_parser.discover_sitemaps(base_url)
# Keep the full list (filtered URLs included) for the sitemap audit
listed = set()
for url in sitemap_urls:
try:
url = normalize_url(url.strip())
except ValueError:
continue
if url.startswith(('http://', 'https://')):
listed.add(url)
self.sitemap_urls = listed
added_count = 0
filtered_count = 0
for url in sitemap_urls:
if self._should_crawl_url(url):
self.link_manager.add_url(url, 0)
# One malformed <loc> must not stop the rest being queued
try:
allowed = self._should_crawl_url(url)
if allowed:
self.link_manager.add_url(url, 0)
except ValueError:
allowed = False
if allowed:
added_count += 1
else:
filtered_count += 1
@@ -560,6 +662,7 @@ class WebCrawler:
self.crawl_id = crawl_id
self.base_url = crawl_data['base_url']
self.base_domain = crawl_data['base_domain']
self.start_url = normalize_url(self.base_url)
# Preserve demo keys across config restore
demo_mode = self.config.get('demo_mode', False)
demo_limit = self.config.get('demo_memory_limit_bytes', 0)
@@ -593,8 +696,16 @@ class WebCrawler:
link_key = f"{link['source_url']}|{link['target_url']}"
self.link_manager.links_set.add(link_key)
# Load issues and restore to issue detector
# Load issues and restore to issue detector. Issues computed at
# the end of a crawl (site-wide analysis, duplicate content) are
# recomputed when the resumed crawl finishes, so the ones from
# the earlier run are dropped rather than saved a second time.
loaded_issues = load_crawl_issues(crawl_id)
recomputed = RECOMPUTED_AT_FINISH
if any(i.get('issue') in recomputed for i in loaded_issues):
from src.crawl_db import delete_issues_by_name
delete_issues_by_name(crawl_id, recomputed)
loaded_issues = [i for i in loaded_issues if i.get('issue') not in recomputed]
if loaded_issues:
self.issue_detector.detected_issues = loaded_issues
@@ -666,6 +777,14 @@ class WebCrawler:
self.stats['discovered'] = len(self.link_manager.all_discovered_urls)
# Re-read the sitemaps for the sitemap audit (and to queue any
# listed URL the interrupted run never reached)
self.sitemap_urls = set()
if self.config.get('discover_sitemaps', True) and not self.config.get('list_mode'):
self._sitemap_discovery_done = False
threading.Thread(target=self._discover_sitemaps_background,
args=(self.base_url,), daemon=True).start()
# Update status to running
set_crawl_status(crawl_id, 'running')
@@ -771,7 +890,8 @@ class WebCrawler:
'memory': self.memory_monitor.get_stats(),
'memory_data': data_sizes,
'demo_stopped': self._demo_limit_reached,
'demo_mode': self.config.get('demo_mode', False)
'demo_mode': self.config.get('demo_mode', False),
'crawl_id': self.crawl_id
}
def get_status(self):
@@ -966,6 +1086,7 @@ class WebCrawler:
try:
result = future.result()
if result:
self._finalize_result(result)
with self.results_lock:
self.crawl_results.append(result)
self.stats['crawled'] += 1
@@ -1049,9 +1170,13 @@ class WebCrawler:
self._detect_duplication_issues(duplication_threshold)
print(f"Duplication detection complete. Total issues: {len(self.issue_detector.get_issues())}")
self._run_crawl_analysis()
# Save final data and set appropriate status
if self.db_save_enabled and self.crawl_id:
self._save_batch_to_db(force=True)
if not self._demo_limit_reached:
self._persist_analysis()
from src.crawl_db import set_crawl_status
if self._demo_limit_reached:
set_crawl_status(self.crawl_id, 'demo_stopped')
@@ -1218,6 +1343,20 @@ class WebCrawler:
]
result['redirected_to'] = final_url
# Indexing directives can arrive as a header instead of a meta
# tag (requests joins repeated headers with ", ")
result['x_robots_tag'] = _header_text(response.headers.get('X-Robots-Tag', ''))
# With redirects not followed, keep the hop so chains and loops
# can be traced through the crawled rows afterwards. A malformed
# Location must not turn a fetched page into an error row.
if 300 <= response.status_code < 400 and response.headers.get('Location'):
try:
result['redirect_target'] = urljoin(
url, _header_text(response.headers['Location']))
except ValueError:
result['redirect_target'] = _header_text(response.headers['Location'])
# Only parse HTML content
if 'text/html' in response.headers.get('content-type', ''):
soup = BeautifulSoup(response.content, 'html.parser')
@@ -1253,6 +1392,10 @@ class WebCrawler:
include_images=self.config.get('crawl_images', False),
base_url=final_url)
# Link: <...>; rel="canonical" (any content type, after the HTML
# tags so the tag stays first when both are present)
_apply_header_canonicals(result, response.headers.get('Link', ''))
# Populate linked_from after all link collection is complete
result['linked_from'] = self.link_manager.get_source_pages(url)
result['response_time'] = round((time.time() - start_time) * 1000, 2)
@@ -1340,9 +1483,16 @@ class WebCrawler:
'hreflang': [],
'schema_org': [],
'linked_from': [],
'javascript_rendered': True
'javascript_rendered': True,
'x_robots_tag': timing.get('x_robots_tag', '')
}
# Real HTTP redirects only (from the request chain); a page.url
# changed by client-side routing is not a redirect
if timing.get('redirects'):
result['redirects'] = timing['redirects']
result['redirected_to'] = final_url
# Parse HTML
soup = BeautifulSoup(html_content, 'html.parser')
@@ -1358,6 +1508,7 @@ class WebCrawler:
self.seo_extractor.extract_hreflang(soup, result)
self.seo_extractor.extract_schema_org(soup, result)
self._apply_custom_extraction(soup, html_content, result)
_apply_header_canonicals(result, timing.get('link_header', ''))
# Collect all links (returns only the ones new to this crawl)
new_links = self.link_manager.collect_all_links(soup, url, self.crawl_results,
@@ -1436,6 +1587,7 @@ class WebCrawler:
try:
result = await task
if result:
self._finalize_result(result)
with self.results_lock:
self.crawl_results.append(result)
self.stats['crawled'] += 1
@@ -1506,9 +1658,13 @@ class WebCrawler:
self._detect_duplication_issues(duplication_threshold)
print(f"Duplication detection complete. Total issues: {len(self.issue_detector.get_issues())}")
self._run_crawl_analysis()
# Save final data and set appropriate status
if self.db_save_enabled and self.crawl_id:
self._save_batch_to_db(force=True)
if not self._demo_limit_reached:
self._persist_analysis()
from src.crawl_db import set_crawl_status
if self._demo_limit_reached:
set_crawl_status(self.crawl_id, 'demo_stopped')
@@ -1531,6 +1687,13 @@ class WebCrawler:
if self.db_save_enabled:
self.unsaved_issues.extend(new_issues)
def _finalize_result(self, result):
"""Per-row fields derived from the row itself, set before the row is
published. Cheap: a few dict lookups, no parsing."""
apply_indexability(result)
if self.sitemap_urls:
result['in_sitemap'] = result.get('url') in self.sitemap_urls
def _update_all_linked_from(self):
"""Update linked_from field for all crawled URLs based on collected source_pages data"""
print("Updating linked_from data for all URLs...")
@@ -1546,6 +1709,61 @@ class WebCrawler:
self.event_log.emit_many('url_update', [self._client_url_data(u) for u in updated])
print(f"Updated linked_from data for {len(updated)} URLs")
def _run_crawl_analysis(self):
"""Site-wide checks once the crawl is done (see crawl_analysis).
Rows are patched in place and journalled as small 'url_patch' events
carrying only the changed fields, so the end-of-crawl update costs
a few bytes per URL rather than a second copy of every row.
"""
if not self.issue_detector or not self.link_manager:
return
started = time.time()
print("Running crawl analysis...")
try:
with self.results_lock:
rows = list(self.crawl_results)
with self.link_manager.links_lock:
links = list(self.link_manager.all_links)
analyzer = CrawlAnalyzer(self.issue_detector._should_exclude)
patches, issues = analyzer.analyze(
rows, links, sitemap_urls=self.sitemap_urls, start_url=self.start_url)
if patches:
self.event_log.emit_many(
'url_patch', [{'url': url, **fields} for url, fields in patches.items()])
if issues:
with self.issue_detector.issues_lock:
self.issue_detector.detected_issues.extend(issues)
self.event_log.emit_many('issue', issues)
self.user_memory.track_issues(issues)
if self.db_save_enabled:
self.unsaved_issues.extend(issues)
print(f"Crawl analysis complete in {time.time() - started:.1f}s: "
f"{len(patches)} rows updated, {len(issues)} issues")
except Exception as e:
print(f"Crawl analysis failed: {e}")
import traceback
traceback.print_exc()
def _persist_analysis(self):
"""Write the end-of-crawl fields to rows saved earlier in the crawl.
Runs after the final batch save, as one executemany over the
(crawl_id, url) index. linked_from goes with it: rows saved mid-crawl
otherwise keep the partial list they had when they were saved.
"""
if not self.db_save_enabled or not self.crawl_id:
return
try:
from src.crawl_db import update_url_analysis
with self.results_lock:
rows = list(self.crawl_results)
update_url_analysis(self.crawl_id, rows)
except Exception as e:
print(f"Error saving crawl analysis: {e}")
def _head_check_new_links(self, new_links, result, depth):
"""HEAD-check a page's new image links and uncrawled external links.
@@ -1670,6 +1888,7 @@ class WebCrawler:
result['is_internal'] = self.link_manager.is_internal(url)
result['linked_from'] = sources
result['link_check_only'] = link_check_only
self._finalize_result(result)
self.crawl_results.append(result)
self.stats['crawled'] += 1
# a result counts as discovered (issue #94)
+5
View File
@@ -29,6 +29,11 @@ Each test pins a bug that reached production once:
| `test_crawl_delay_is_honoured` | The crawl delay setting is ignored with JavaScript rendering off, so sites get hit as fast as concurrency allows |
| `test_list_mode_fetches_only_the_list` | List mode follows links, probes sitemaps, drops a listed URL, fetches a robots.txt-disallowed URL, or misses URLs on a second site |
| `test_custom_extraction` | CSS/XPath extractors return wrong values, break on pages without matches, lose their per-extractor export columns, or save with an invalid selector |
| `test_site_wide_analysis` | Indexability ignores X-Robots-Tag; duplicate title/meta/H1, redirect chains and loops, broken-link sources, canonical chains, inlinks, Link Score or the sitemap/orphan audit go wrong; analysis patches reach the UI before their rows |
| `test_crawl_analysis_scales_linearly` | The end-of-crawl analysis turns quadratic on templated sites and holds a large crawl in "finishing up" |
| `test_hostile_input_regressions` | One malformed `href`, `Location` or sitemap `<loc>` loses a whole page or the rest of the sitemap; 204 counts as indexable; a `javascript:` canonical marks a page canonicalised; equally linked pages score 0; a corrupt DB value empties a loaded crawl |
| `test_canonicals_and_titles` | Repeated or conflicting canonicals (tags or `Link` headers) go unreported, conflicting ones still mark the page canonicalised, a header-only canonical is missed, or titles inside SVG/`<object>`/`<iframe>` count as page titles |
| `test_analysis_persists_and_crawls_compare` | Analysis fields or the final `linked_from` are lost on reload, crawl comparison misreports changes or leaks another user's crawls, or a resumed crawl saves its end-of-crawl issues twice |
## crawl_harness.py
+5
View File
@@ -93,6 +93,11 @@ class Client:
f"'url_update' for a url never sent: {row['url']}")
self.urls[row['url']] = row
self.url_updates += 1
elif kind == 'url_patch':
check(row['url'] in self.urls,
f"'url_patch' for a url never sent: {row['url']}")
self.urls[row['url']] = {**self.urls[row['url']], **row}
self.url_updates += 1
elif kind == 'link':
key = row['source_url'] + '|' + row['target_url']
check(key not in self.links, f"duplicate 'link' event for {key}")
+491 -1
View File
@@ -57,7 +57,8 @@ def png():
def make_handler(routes, hits=None, slow_paths=(), slow_seconds=0.0):
"""Build a handler serving `routes`: path -> html str, bytes, or (code, location)."""
"""Build a handler serving `routes`: path -> html str, bytes, (code, location),
or {'body': html str, 'headers': {name: value}} for extra response headers."""
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
@@ -90,6 +91,16 @@ def make_handler(routes, hits=None, slow_paths=(), slow_seconds=0.0):
elif isinstance(route, bytes):
ctype = 'image/png' if self.path.endswith('.png') else 'application/octet-stream'
self._send(200, route, ctype)
elif isinstance(route, dict):
body = route['body'].encode()
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', str(len(body)))
for name, value in route.get('headers', {}).items():
self.send_header(name, value)
self.end_headers()
if self.command == 'GET':
self.wfile.write(body)
else:
self._send(200, route.encode())
@@ -929,6 +940,480 @@ def test_self_hosted_accounts_without_email():
tmp.cleanup()
def _page(title, body='', head=''):
return f'<html><head><title>{title}</title>{head}</head><body>{body}</body></html>'
def _analysis_site(port, external_port):
"""Routes for the site-wide analysis fixtures. Returned as a dict so a
test can change the site between two crawls."""
links = ''.join(f'<a href="{p}">{p}</a>' for p in (
'/a', '/b', '/dup1', '/dup2', '/noindex-hdr', '/canon', '/canon2', '/canon-target',
'/redir1', '/redir-bad', '/loop1', '/broken', '/multi-h1'))
dup_head = '<meta name="description" content="The same description on two pages">'
return {
'/': _page('Home', '<h1>Home</h1>' + links
+ f'<a href="http://127.0.0.1:{external_port}/gone">gone</a>'),
'/a': _page('Page A', '<h1>A</h1><a href="/">home</a>'),
'/b': _page('Page B', '<h1>B</h1><a href="/a">a</a>'),
'/dup1': _page('Same Title Here', '<h1>Same H1</h1>', dup_head),
'/dup2': _page('Same Title Here', '<h1>Same H1</h1>', dup_head),
'/noindex-hdr': {'body': _page('Header Noindex', '<h1>N</h1>'),
'headers': {'X-Robots-Tag': 'googlebot: noindex'}},
'/canon': _page('Canon', '<h1>C</h1>', '<link rel="canonical" href="/canon-target">'),
'/canon2': _page('Canon Two', '<h1>C2</h1>', '<link rel="canonical" href="/canon">'),
'/redir1': (301, '/redir2'),
'/redir2': (301, '/a'),
'/redir-bad': (301, '/nowhere'),
'/loop1': (302, '/loop2'),
'/loop2': (302, '/loop1'),
'/multi-h1': _page('Multi', '<h1>One</h1><h1>Two</h1>'),
'/orphan': _page('Orphan', '<h1>O</h1>'),
'/sitemap.xml': ('<?xml version="1.0" encoding="UTF-8"?>'
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
+ ''.join(f'<url><loc>http://127.0.0.1:{port}{p}</loc></url>'
for p in ('/', '/a', '/orphan', '/noindex-hdr', '/redir1'))
+ '</urlset>'),
}
def test_site_wide_analysis():
"""Screaming Frog style crawl analysis: indexability (incl. X-Robots-Tag),
duplicate title/meta/H1, redirect chains and loops, inlinks and Link
Score, broken-link sources, canonical and sitemap checks."""
from collections import Counter
site, external = BASE_PORT + 16, BASE_PORT + 17
a = serve(make_handler(_analysis_site(site, external)), site)
b = serve(make_handler({}), external)
base = f'http://127.0.0.1:{site}'
try:
crawler = crawl(base + '/', discover_sitemaps=True)
rows = {r['url']: r for r in crawler.crawl_results}
issues = crawler.issue_detector.get_issues()
def has(path, name, contains=''):
return any(i['url'] == base + path and i['issue'] == name and contains in i['details']
for i in issues)
def flagged(name):
return sorted(i['url'].replace(base, '') for i in issues if i['issue'] == name)
def index_of(path):
r = rows.get(base + path, {})
return r.get('indexability'), r.get('indexability_status')
result('indexability: plain page is indexable', index_of('/a') == ('Indexable', ''),
str(index_of('/a')))
result('indexability: X-Robots-Tag noindex is read',
index_of('/noindex-hdr') == ('Non-Indexable', 'noindex (X-Robots-Tag)'),
str(index_of('/noindex-hdr')))
result('indexability: canonicalised, redirected and 404 pages',
index_of('/canon')[1] == 'Canonicalised' and index_of('/redir1')[1] == 'Redirected'
and index_of('/broken')[1] == 'Client Error',
f"{index_of('/canon')} {index_of('/redir1')} {index_of('/broken')}")
result('X-Robots-Tag noindex raises the noindex issue',
has('/noindex-hdr', 'Noindex Tag Present', 'X-Robots-Tag'))
result('duplicate title: exactly the two pages sharing it',
flagged('Duplicate Title') == ['/dup1', '/dup2'], str(flagged('Duplicate Title')))
result('duplicate meta description and H1 are reported too',
flagged('Duplicate Meta Description') == ['/dup1', '/dup2']
and flagged('Duplicate H1') == ['/dup1', '/dup2'],
f"{flagged('Duplicate Meta Description')} {flagged('Duplicate H1')}")
result('multiple H1 tags', flagged('Multiple H1 Tags') == ['/multi-h1']
and rows[base + '/multi-h1'].get('h1_count') == 2, str(flagged('Multiple H1 Tags')))
result('redirect chain of two hops', has('/redir1', 'Redirect Chain', '2 hops'),
str(flagged('Redirect Chain')))
result('redirect to a broken URL', flagged('Redirect to Broken URL') == ['/redir-bad'],
str(flagged('Redirect to Broken URL')))
result('redirect loop', flagged('Redirect Loop') == ['/loop1'], str(flagged('Redirect Loop')))
# /canon-target, /broken and /redir-bad end in 404, /loop1 never answers
result('broken internal links reported on the linking page',
flagged('Broken Internal Links') == ['/'] and has('/', 'Broken Internal Links', '4 links'),
next((i['details'] for i in issues if i['issue'] == 'Broken Internal Links'), 'none'))
result('broken external links reported on the linking page',
has('/', 'Broken External Links', '/gone'), str(flagged('Broken External Links')))
result('internal links to redirects reported on the linking page',
has('/', 'Internal Links to Redirects', '/redir1'))
result('canonical pointing at a 404', flagged('Canonical Points to Non-Indexable URL') == ['/canon'],
str(flagged('Canonical Points to Non-Indexable URL')))
result('canonical chain', flagged('Canonical Chain') == ['/canon2'], str(flagged('Canonical Chain')))
inlinks_a = rows[base + '/a'].get('inlinks')
result('unique inlinks counted (redirect rows pass on no links)',
inlinks_a == 2 and rows[base + '/'].get('inlinks') == 1,
f"/a={inlinks_a} /={rows[base + '/'].get('inlinks')}")
scores = [r.get('link_score') for r in rows.values()
if r.get('is_internal') and r.get('link_score') is not None]
result('link score is 0-100 and favours better linked pages',
scores and max(scores) == 100 and min(scores) >= 0
and rows[base + '/a']['link_score'] > rows[base + '/multi-h1']['link_score'],
f"/a={rows[base + '/a'].get('link_score')} /multi-h1={rows[base + '/multi-h1'].get('link_score')}")
result('sitemap membership recorded',
rows[base + '/'].get('in_sitemap') is True and rows[base + '/b'].get('in_sitemap') is False)
result('orphan page found from the sitemap only', flagged('Orphan Page (Sitemap Only)') == ['/orphan'],
str(flagged('Orphan Page (Sitemap Only)')))
result('non-indexable URLs in the sitemap',
flagged('Non-Indexable URL in Sitemap') == ['/noindex-hdr', '/redir1'],
str(flagged('Non-Indexable URL in Sitemap')))
result('indexable pages missing from the sitemap include /b',
'/b' in flagged('Indexable Page Not in Sitemap')
and '/a' not in flagged('Indexable Page Not in Sitemap'))
repeated = [k for k, n in Counter((i['url'], i['issue']) for i in issues).items() if n > 1]
result('no issue repeated for the same URL', not repeated, str(repeated[:3]))
# Journal: analysis results go out as small patches, never for a
# row the client has not been sent
sent, bad, patches = set(), [], 0
for event in crawler.event_log._events:
if event['kind'] == 'url':
sent.add(event['data']['url'])
elif event['kind'] == 'url_patch':
patches += 1
if event['data']['url'] not in sent:
bad.append(event['data']['url'])
result('analysis patches follow their rows in the journal', patches > 0 and not bad,
f'{patches} patches, {len(bad)} orphaned')
# Redirects not followed: chains and loops traced through the rows
listed = [base + p for p in ('/redir1', '/redir2', '/a', '/loop1', '/loop2',
'/redir-bad', '/nowhere')]
crawler = crawl(base + '/', url_list=listed, follow_redirects=False)
issues = crawler.issue_detector.get_issues()
result('unfollowed: chain traced through the 3xx rows', has('/redir1', 'Redirect Chain', '2 hops'),
str(flagged('Redirect Chain')))
result('unfollowed: loop traced through the 3xx rows',
flagged('Redirect Loop') == ['/loop1', '/loop2'], str(flagged('Redirect Loop')))
result('unfollowed: redirect ending in a 404',
flagged('Redirect to Broken URL') == ['/redir-bad'], str(flagged('Redirect to Broken URL')))
finally:
a.shutdown()
b.shutdown()
def test_crawl_analysis_scales_linearly():
"""The end-of-crawl analysis must not hold a large crawl in "finishing
up": 20,000 pages and ~200,000 links, all templated alike."""
from src.core.crawl_analysis import CrawlAnalyzer
count = 20000
rows = [{'url': f'https://x.au/p{i}', 'status_code': 200, 'content_type': 'text/html',
'is_internal': True, 'title': f'Product {i % 500}', 'meta_description': 'Same for all',
'h1': f'Product {i}', 'canonical_url': f'https://x.au/p{i}'} for i in range(count)]
links = []
for i in range(count):
for step in (1, 7, 31, 101, 499, 997, 1999, 4999, 9973, 13):
links.append({'source_url': f'https://x.au/p{i}', 'target_url': f'https://x.au/p{(i + step) % count}',
'is_internal': True, 'placement': 'body', 'target_status': 200})
started = time.time()
analyzer = CrawlAnalyzer()
patches, issues = analyzer.analyze(rows, links, sitemap_urls={f'https://x.au/p{i}' for i in range(0, count, 2)},
start_url='https://x.au/p0')
elapsed = time.time() - started
# ~2s on a laptop; an O(group²) slip (examples listed per duplicate
# page) once made this 27s
result('20k pages / 200k links analysed quickly', elapsed < 10 and not analyzer.link_score_truncated,
f'{elapsed:.1f}s, {len(patches)} patches, {len(issues)} issues')
per_page = sum(1 for i in issues if i['issue'] == 'Duplicate Meta Description')
result('one duplicate issue per page, not per pair', per_page == count, f'{per_page}')
def test_analysis_persists_and_crawls_compare():
"""Analysis fields survive a save and reload, and two saved crawls of a
site can be compared through the API."""
import tempfile
os.environ.setdefault('LOCAL_MODE', 'true')
import main as app_module
from src import auth_db, crawl_db
site, external = BASE_PORT + 18, BASE_PORT + 19
routes = _analysis_site(site, external)
a = serve(make_handler(routes), site)
b = serve(make_handler({}), external)
base = f'http://127.0.0.1:{site}'
saved = (auth_db.DB_FILE, crawl_db.DB_FILE)
tmp = tempfile.TemporaryDirectory()
try:
auth_db.DB_FILE = crawl_db.DB_FILE = os.path.join(tmp.name, 'compare.db')
auth_db.init_db()
def saved_crawl():
crawler = WebCrawler()
crawler.config.update({
'delay': 0.02, 'concurrency': 5, 'max_urls': 200, 'max_depth': 4,
'crawl_external': False, 'discover_sitemaps': True, 'respect_robots': False})
# Save every row as it arrives, so rows are in SQLite before the
# analysis runs and only the end-of-crawl UPDATE can fill it in
crawler.batch_save_size = 1
ok, message = crawler.start_crawl(base + '/', user_id=1, session_id='fixture-session')
assert ok, message
deadline = time.time() + 120
while crawler.is_running and time.time() < deadline:
time.sleep(0.1)
return crawler
first = saved_crawl()
loaded = {r['url']: r for r in crawl_db.load_crawled_urls(first.crawl_id)}
page_a = loaded.get(base + '/a', {})
result('reloaded rows keep indexability, inlinks, link score, sitemap flag',
page_a.get('indexability') == 'Indexable' and page_a.get('inlinks') == 2
and isinstance(page_a.get('link_score'), int) and page_a.get('in_sitemap') is True,
str({k: page_a.get(k) for k in ('indexability', 'inlinks', 'link_score', 'in_sitemap')}))
result('reloaded rows keep X-Robots-Tag and the final linked_from',
loaded.get(base + '/noindex-hdr', {}).get('x_robots_tag') == 'googlebot: noindex'
and sorted(page_a.get('linked_from') or []) == sorted([base + '/', base + '/b']),
str(page_a.get('linked_from')))
# The site changes: a page goes, one appears, a title changes, a page
# turns noindex and the homepage gains a broken link
routes['/'] = routes['/'].replace('<a href="/b">/b</a>', '<a href="/new">/new</a>'
'<a href="/also-broken">x</a>')
routes['/new'] = _page('New Page', '<h1>New</h1>')
routes['/a'] = _page('Page A Renamed', '<h1>A</h1><a href="/">home</a>')
routes['/multi-h1'] = _page('Multi', '<h1>One</h1>', '<meta name="robots" content="noindex">')
second = saved_crawl()
client = app_module.app.test_client()
with client.session_transaction() as s:
s['user_id'] = 1
s['username'] = 'fixture'
s['tier'] = 'admin'
resp = client.get(f'/api/crawls/compare?previous={first.crawl_id}&current={second.crawl_id}')
data = resp.get_json() or {}
changes = data.get('changes') or []
def changed(kind, path):
return [c for c in changes if c['change'] == kind and c['url'] == base + path]
result('compare: added and removed URLs',
bool(changed('added', '/new')) and bool(changed('removed', '/b')),
str(data.get('summary', data.get('error'))))
title = changed('title', '/a')
result('compare: title change with both values',
bool(title) and title[0]['previous'] == 'Page A' and title[0]['current'] == 'Page A Renamed',
str(title))
result('compare: indexability change',
any(c['current'].startswith('Non-Indexable (noindex)') for c in changed('indexability', '/multi-h1')),
str(changed('indexability', '/multi-h1')))
result('compare: new issue on an existing URL',
any(c['current'] == 'Noindex Tag Present' for c in changed('new_issue', '/multi-h1')),
str(changed('new_issue', '/multi-h1')))
result('compare: resolved issue on an existing URL',
any(c['previous'] == 'Multiple H1 Tags' for c in changed('resolved_issue', '/multi-h1')))
result('compare: issue totals per issue name',
any(i['issue'] == 'Noindex Tag Present' and i['delta'] == 1
for i in data.get('issue_changes') or []))
result('compare: unchanged pages produce no rows', not [c for c in changes
if c['url'] == base + '/dup1'])
csv_resp = client.get(f'/api/crawls/compare?previous={first.crawl_id}'
f'&current={second.crawl_id}&format=csv')
lines = csv_resp.data.decode().strip().splitlines()
result('compare: CSV has a header and one line per change',
csv_resp.status_code == 200 and lines[0] == 'url,change,previous,current'
and len(lines) == data.get('total_changes', -1) + 1, f'{len(lines)} lines')
with client.session_transaction() as s:
s['user_id'] = 2
denied = client.get(f'/api/crawls/compare?previous={first.crawl_id}&current={second.crawl_id}')
result("compare: another user's crawls are refused", denied.status_code == 403,
str(denied.status_code))
# Resuming a crawl whose analysis already ran recomputes the
# site-wide issues instead of saving them a second time
from collections import Counter
before = Counter((i['url'], i['issue']) for i in crawl_db.load_crawl_issues(second.crawl_id))
crawl_db.set_crawl_status(second.crawl_id, 'paused')
resumed = WebCrawler()
ok, message = resumed.resume_from_database(second.crawl_id, user_id=1)
deadline = time.time() + 120
while ok and resumed.is_running and time.time() < deadline:
time.sleep(0.1)
after = Counter((i['url'], i['issue']) for i in crawl_db.load_crawl_issues(second.crawl_id))
repeated = [k for k, n in after.items() if n > 1 and before.get(k, 0) < n]
result('resume: site-wide issues are recomputed, not duplicated',
ok and not repeated and after[(base + '/', 'Broken Internal Links')] == 1,
message if not ok else str(repeated[:3]))
finally:
auth_db.DB_FILE, crawl_db.DB_FILE = saved
a.shutdown()
b.shutdown()
tmp.cleanup()
def test_hostile_input_regressions():
"""Bugs found by fuzzing the crawler and the analysis with malformed input."""
import tempfile
from src.crawler import _header_text
from src.core.crawl_analysis import CrawlAnalyzer, indexability
from src.core.crawl_compare import compare_crawls
from src import auth_db, crawl_db
site = BASE_PORT + 20
base = f'http://127.0.0.1:{site}'
routes = {
'/': html('<a href="http://[bad/">bad</a><a href="/after">after</a>'
'<a href="/bad-location">r</a><a href="/nocontent">n</a><a href="/jscanon">j</a>'),
'/after': html('after'),
'/bad-location': (302, 'http://[bad/x'),
'/jscanon': '<html><head><title>J</title><link rel="canonical" href="javascript:void(0)"></head></html>',
'/sitemap.xml': ('<?xml version="1.0"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
'<url><loc>http://[bad</loc></url>'
f'<url><loc>{base}/listed-only</loc></url></urlset>'),
'/listed-only': html('listed'),
}
class NoContent(make_handler(routes)):
def do_GET(self):
if self.path == '/nocontent':
self.send_response(204)
self.end_headers()
return
super().do_GET()
do_HEAD = do_GET
srv = serve(NoContent, site)
try:
crawler = crawl(base + '/', follow_redirects=False, discover_sitemaps=True)
rows = {r['url']: r for r in crawler.crawl_results}
home = rows.get(base + '/', {})
result('a malformed href does not turn the page into a failed fetch',
home.get('status_code') == 200 and base + '/after' in rows,
f"{home.get('status_code')} {home.get('error')}")
bad = rows.get(base + '/bad-location', {})
result('a malformed Location is kept, not turned into an error row',
bad.get('status_code') == 302 and bad.get('redirect_target') == 'http://[bad/x',
f"{bad.get('status_code')} {bad.get('error')}")
result('204 No Content is not indexable',
rows.get(base + '/nocontent', {}).get('indexability_status') == 'Non-200 Status (204)')
result('a javascript: canonical does not canonicalise the page',
rows.get(base + '/jscanon', {}).get('indexability') == 'Indexable')
result('a malformed sitemap <loc> does not stop the rest being queued',
base + '/listed-only' in rows and all(u.startswith('http') for u in crawler.sitemap_urls),
str(sorted(crawler.sitemap_urls)))
finally:
srv.shutdown()
result('UTF-8 header bytes are decoded as UTF-8', _header_text('nöindex') == 'nöindex'
and _header_text('noindex') == 'noindex' and _header_text('ü') == 'ü')
def scores(n, edges):
rows = [{'url': f'https://x.au/{i}', 'status_code': 200, 'content_type': 'text/html',
'is_internal': True} for i in range(n)]
links = [{'source_url': f'https://x.au/{a}', 'target_url': f'https://x.au/{b}',
'is_internal': True, 'placement': 'body'} for a, b in edges]
CrawlAnalyzer().analyze(rows, links)
return [r['link_score'] for r in rows]
complete = scores(7, [(a, b) for a in range(7) for b in range(7) if a != b])
result('equally linked pages share one Link Score, not 0', set(complete) == {100}, str(complete))
try:
compare_crawls([{'url': 'https://x.au/a'}], [{'url': 'https://x.au/a'}, {'url': None}],
[('https://x.au/a', None, None)], [('https://x.au/a', 'X', 'error')])
result('compare tolerates NULL issue names and URL-less rows', True)
except Exception as e:
result('compare tolerates NULL issue names and URL-less rows', False, repr(e))
result('indexability of a row with no status is "No Response"',
indexability({'url': 'https://x.au/', 'status_code': None}) == ('Non-Indexable', 'No Response'))
saved = (auth_db.DB_FILE, crawl_db.DB_FILE)
tmp = tempfile.TemporaryDirectory()
try:
auth_db.DB_FILE = crawl_db.DB_FILE = os.path.join(tmp.name, 'corrupt.db')
auth_db.init_db()
cid = crawl_db.create_crawl(1, 's', 'https://x.au', 'x.au', {})
crawl_db.save_url_batch(cid, [{'url': f'https://x.au/{i}', 'status_code': 200} for i in range(3)])
with crawl_db.get_db() as conn:
conn.execute("UPDATE crawled_urls SET analysis = 'null' WHERE url = 'https://x.au/0'")
conn.execute("""UPDATE crawled_urls SET analysis = '{"url": "https://evil/"}' WHERE url = 'https://x.au/1'""")
loaded = crawl_db.load_crawled_urls(cid)
result('a corrupt analysis value loses nothing and overrides nothing',
sorted(r['url'] for r in loaded) == ['https://x.au/0', 'https://x.au/1', 'https://x.au/2'],
str([r['url'] for r in loaded]))
finally:
auth_db.DB_FILE, crawl_db.DB_FILE = saved
tmp.cleanup()
def test_canonicals_and_titles():
"""Multiple and conflicting canonicals (HTML tags and Link headers), and
title counting that skips embedded documents/graphics."""
site = BASE_PORT + 21
base = f'http://127.0.0.1:{site}'
def canon(*hrefs, rel='canonical'):
return ''.join(f'<link rel="{rel}" href="{h}">' for h in hrefs)
pages = {
'/same': _page('Same', head=canon('/same', f'{base}/same')),
'/conflict': _page('Conflict', head=canon('/a', '/b')),
'/mixed': {'body': _page('Mixed', head=canon('/a')),
'headers': {'Link': f'<{base}/b>; rel="canonical"'}},
'/header-only': {'body': _page('Header only'),
'headers': {'Link': f'<{base}/a>; rel="canonical", <{base}/x.css>; rel="preload"'}},
'/junk-first': _page('Junk first', head=canon('', '/a')),
'/case': _page('Case', head=canon('/a', rel='CANONICAL') + canon('/a', rel='alternate canonical')),
'/twohead': '<html><head><title>One</title></head><head><title>Two</title></head><body></body></html>',
'/embedded': _page('Real', '<svg><title>icon</title></svg><object><title>obj</title></object>'
'<iframe><title>frame</title></iframe>'),
# <embed> is a void element: nothing can be inside it, so a title
# written after it is an ordinary (second) title, in browsers too
'/after-embed': _page('Real', '<embed src="x.swf"><title>stray</title>'),
'/svg-only': '<html><head></head><body><svg><title>icon</title></svg></body></html>',
'/a': _page('A'), '/b': _page('B'),
}
pages['/'] = _page('Home', ''.join(f'<a href="{p}">{p}</a>' for p in pages))
srv = serve(make_handler(pages), site)
try:
crawler = crawl(base + '/')
rows = {r['url'].replace(base, ''): r for r in crawler.crawl_results}
issues = crawler.issue_detector.get_issues()
def flagged(name):
return sorted(i['url'].replace(base, '') for i in issues if i['issue'] == name)
result('same URL declared twice: info, page stays indexable',
flagged('Multiple Canonical Tags') == ['/case', '/junk-first', '/same']
and rows['/same']['indexability'] == 'Indexable',
str(flagged('Multiple Canonical Tags')))
result('conflicting tags, and tag vs Link header, are errors',
flagged('Conflicting Canonicals') == ['/conflict', '/mixed'],
str(flagged('Conflicting Canonicals')))
result('conflicting canonicals are ignored, as search engines do',
rows['/conflict']['indexability'] == 'Indexable'
and '/conflict' not in flagged('Canonical URL Different'),
str((rows['/conflict']['indexability'], rows['/conflict']['indexability_status'])))
result('Link header canonical is used when the HTML has none',
rows['/header-only'].get('canonical_url') == f'{base}/a'
and rows['/header-only']['indexability_status'] == 'Canonicalised'
and '/header-only' not in flagged('Missing Canonical URL')
and rows['/mixed'].get('canonical_header') == f'{base}/b',
str(rows['/header-only'].get('canonical_url')))
result('an empty href among canonicals defers to the valid one',
rows['/junk-first']['indexability_status'] == 'Canonicalised')
result('rel is matched case-insensitively and as a token list',
rows['/case'].get('canonical_count') == 2)
result('titles in a second <head> count', rows['/twohead'].get('title_count') == 2
and '/twohead' in flagged('Multiple Title Tags'))
result('titles inside svg, object and iframe do not count',
rows['/embedded'].get('title_count') == 1 and rows['/embedded']['title'] == 'Real',
str(rows['/embedded'].get('title_count')))
result('a title after a (void) <embed> is a real second title',
rows['/after-embed'].get('title_count') == 2)
result('an SVG title is not the page title',
rows['/svg-only']['title'] == '' and '/svg-only' in flagged('Missing Title Tag'))
finally:
srv.shutdown()
def _playwright_available():
try:
import playwright # noqa: F401
@@ -954,6 +1439,11 @@ TESTS = (
test_ngram_analyzer,
test_ngram_extraction,
test_self_hosted_accounts_without_email,
test_site_wide_analysis,
test_crawl_analysis_scales_linearly,
test_analysis_persists_and_crawls_compare,
test_hostile_input_regressions,
test_canonicals_and_titles,
)
+117
View File
@@ -206,6 +206,123 @@ body {
cursor: pointer;
}
/* Crawl comparison */
.compare-bar {
display: flex;
gap: 10px;
flex-wrap: wrap;
justify-content: center;
align-items: center;
padding: 15px 20px 0;
}
.compare-label {
color: #cbd5e1;
font-size: 14px;
display: flex;
align-items: center;
gap: 8px;
}
.compare-input {
padding: 6px 12px;
border-radius: 6px;
border: 1px solid #4b5563;
background: #1f2937;
color: white;
font-size: 13px;
max-width: 420px;
}
.compare-btn {
padding: 8px 16px;
border-radius: 6px;
border: 1px solid #4b5563;
background: #1f2937;
color: white;
cursor: pointer;
font-size: 14px;
}
.compare-btn-primary {
background: #7c3aed;
border-color: #7c3aed;
}
.compare-status {
color: #94a3b8;
font-size: 13px;
}
.compare-summary {
padding: 12px 20px 0;
}
.compare-summary:empty {
display: none;
}
.compare-cards {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 10px;
}
.compare-card {
padding: 8px 12px;
border-radius: 8px;
border: 1px solid #374151;
background: rgba(255, 255, 255, 0.03);
color: #e2e8f0;
font-size: 13px;
cursor: pointer;
text-align: left;
}
.compare-card strong {
display: block;
font-size: 18px;
}
.compare-card.active {
border-color: #7c3aed;
background: rgba(124, 58, 237, 0.15);
}
.compare-card.zero {
opacity: 0.5;
}
.compare-issues {
max-height: 170px;
overflow: auto;
border: 1px solid #374151;
border-radius: 8px;
}
.compare-issues table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.compare-issues th,
.compare-issues td {
padding: 5px 10px;
text-align: left;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.compare-issues th {
position: sticky;
top: 0;
background: #1f2937;
}
.compare-delta-up { color: #ef4444; }
.compare-delta-down { color: #10b981; }
/* Custom extraction */
.extraction-empty {
padding: 14px 16px;
+339 -4
View File
@@ -37,7 +37,8 @@ let virtualScrollers = {
externalLinks: null,
issues: null,
extraction: null,
ngrams: null
ngrams: null,
compare: null
};
// 'spider' follows links from one URL; 'list' checks a pasted list
@@ -65,6 +66,11 @@ const TABLE_COLUMNS = {
{ key: 'links', label: 'Links (Int/Ext)', sortable: true },
{ key: 'images', label: 'Images', sortable: true },
{ key: 'javascript_rendered', label: 'JS', sortable: true },
{ key: 'indexability', label: 'Indexability', sortable: true },
{ key: 'indexability_status', label: 'Indexability Status', sortable: true },
{ key: 'inlinks', label: 'Inlinks', sortable: true },
{ key: 'link_score', label: 'Link Score', sortable: true },
{ key: 'in_sitemap', label: 'In Sitemap', sortable: true },
{ key: 'details', label: 'Details', sortable: false }
],
internal: [
@@ -72,7 +78,10 @@ const TABLE_COLUMNS = {
{ key: 'status_code', label: 'Status', sortable: true },
{ key: 'content_type', label: 'Content Type', sortable: true },
{ key: 'size', label: 'Size', sortable: true },
{ key: 'title', label: 'Title', sortable: true }
{ key: 'title', label: 'Title', sortable: true },
{ key: 'indexability', label: 'Indexability', sortable: true },
{ key: 'inlinks', label: 'Inlinks', sortable: true },
{ key: 'link_score', label: 'Link Score', sortable: true }
],
external: [
{ key: 'url', label: 'Address', sortable: true },
@@ -983,6 +992,30 @@ function rawOverviewValue(urlData, key) {
case 'links': return Number(urlData.internal_links || 0) + Number(urlData.external_links || 0);
case 'images': return (urlData.images || []).length;
case 'javascript_rendered': return urlData.javascript_rendered ? 1 : 0;
default: return rawAnalysisValue(urlData, key);
}
}
// Unique inlinks. The exact count arrives with the end-of-crawl analysis;
// until then the live linked_from length is a close stand-in (O(1), as
// this runs inside sort comparators).
function inlinkCount(urlData) {
if (typeof urlData.inlinks === 'number') return urlData.inlinks;
if (!urlData.is_internal) return null;
return (urlData.linked_from || []).length;
}
// Columns shared by the Overview and Internal tables
function rawAnalysisValue(urlData, key) {
switch (key) {
case 'indexability': return urlData.indexability || '';
case 'indexability_status': return urlData.indexability_status || '';
case 'inlinks': return inlinkCount(urlData);
case 'link_score': return typeof urlData.link_score === 'number' ? urlData.link_score : null;
case 'in_sitemap':
if (urlData.in_sitemap === true) return 'Yes';
if (urlData.in_sitemap === false) return 'No';
return '';
default: return '';
}
}
@@ -994,7 +1027,7 @@ function rawUrlValue(urlData, key) {
case 'content_type': return urlData.content_type || '';
case 'size': return Number(urlData.size || 0);
case 'title': return urlData.title || '';
default: return '';
default: return rawAnalysisValue(urlData, key);
}
}
@@ -1021,6 +1054,7 @@ function displayColumnValue(tableName, urlData, key) {
if (key === 'javascript_rendered') return raw ? '✅ JS' : '';
}
if (raw === null || raw === undefined) return '';
return String(raw);
}
@@ -1366,6 +1400,16 @@ function initializeVirtualScrollers() {
console.log('N-grams virtual scroller initialized');
}
// Crawl comparison table
const compareContainer = document.querySelector('#compare-tab .table-container');
if (compareContainer && compareContainer.querySelector('tbody')) {
virtualScrollers.compare = new VirtualScroller(compareContainer, {
rowHeight: 60,
buffer: 25,
renderRow: renderCompareRow
});
}
// Issues table
const issuesContainer = document.querySelector('#issues-tab .table-container');
if (issuesContainer && issuesContainer.querySelector('tbody')) {
@@ -1546,6 +1590,237 @@ function exportNgrams() {
URL.revokeObjectURL(link.href);
}
// ========================================
// Crawl comparison
// ========================================
let compareResult = null;
let compareKindFilter = 'all';
let compareLabels = {};
const compareState = { currentId: null, previousId: null };
async function loadCompareOptions() {
const select = document.getElementById('compareCrawlSelect');
const statusEl = document.getElementById('compareStatus');
if (!select) return;
try {
const [statusResponse, listResponse] = await Promise.all([
fetch('/api/crawl_status?stats_only=1'),
fetch('/api/crawls/list?limit=200')
]);
const status = await statusResponse.json();
const list = await listResponse.json();
const currentId = status.crawl_id;
compareState.currentId = currentId;
if (!list.success) {
statusEl.textContent = list.error || 'Could not load saved crawls';
return;
}
const current = (list.crawls || []).find(c => c.id === currentId);
const currentDomain = current ? current.base_domain : null;
const others = (list.crawls || []).filter(c => c.id !== currentId);
// Same site first, newest first within each group (the list is
// already newest first)
others.sort((a, b) => (b.base_domain === currentDomain) - (a.base_domain === currentDomain));
const previous = select.value;
select.innerHTML = '';
if (!currentId) {
statusEl.textContent = 'Run or load a crawl first; it becomes the "current" side.';
} else if (!others.length) {
statusEl.textContent = 'No other saved crawls to compare with yet.';
} else {
statusEl.textContent = '';
}
others.forEach(c => {
const option = document.createElement('option');
option.value = c.id;
const when = c.started_at ? String(c.started_at).replace('T', ' ').slice(0, 16) : '';
option.textContent = `#${c.id} ${c.base_url} · ${when} · ${c.urls_crawled || 0} URLs` +
(c.status && c.status !== 'completed' ? ` (${c.status})` : '');
select.appendChild(option);
});
if (previous && others.some(c => String(c.id) === previous)) {
select.value = previous;
}
} catch (error) {
statusEl.textContent = 'Could not load saved crawls';
}
}
async function runCompare() {
const select = document.getElementById('compareCrawlSelect');
const statusEl = document.getElementById('compareStatus');
if (!select || !select.value) {
statusEl.textContent = 'Pick a crawl to compare with.';
return;
}
statusEl.textContent = 'Comparing…';
const params = new URLSearchParams({ previous: select.value });
try {
const response = await fetch('/api/crawls/compare?' + params.toString());
const data = await response.json();
if (!data.success) {
statusEl.textContent = data.error || 'Comparison failed';
return;
}
compareResult = data;
compareLabels = {};
data.change_kinds.forEach(kind => { compareLabels[kind.key] = kind.label; });
compareState.previousId = data.previous.id;
compareState.currentId = data.current.id;
compareKindFilter = 'all';
const filter = document.getElementById('compareChangeFilter');
filter.innerHTML = '<option value="all">All changes</option>';
data.change_kinds.forEach(kind => {
const option = document.createElement('option');
option.value = kind.key;
option.textContent = `${kind.label} (${data.summary.changes[kind.key] || 0})`;
filter.appendChild(option);
});
statusEl.textContent = `#${data.previous.id} → #${data.current.id}: ` +
`${data.total_changes.toLocaleString()} change(s)` +
(data.truncated ? ` (showing the first ${data.changes.length.toLocaleString()}; export CSV for all)` : '');
renderCompareSummary(data);
filterCompareChanges();
} catch (error) {
statusEl.textContent = 'Comparison failed';
}
}
function renderCompareSummary(data) {
const container = document.getElementById('compareSummary');
container.innerHTML = '';
const cards = document.createElement('div');
cards.className = 'compare-cards';
const totals = document.createElement('div');
totals.className = 'compare-card';
totals.style.cursor = 'default';
const strong = document.createElement('strong');
strong.textContent = `${data.summary.previous_urls.toLocaleString()} → ${data.summary.current_urls.toLocaleString()}`;
totals.appendChild(strong);
totals.appendChild(document.createTextNode('URLs'));
cards.appendChild(totals);
data.change_kinds.forEach(kind => {
const count = data.summary.changes[kind.key] || 0;
const card = document.createElement('button');
card.type = 'button';
card.className = 'compare-card' + (count ? '' : ' zero');
card.dataset.kind = kind.key;
const value = document.createElement('strong');
value.textContent = count.toLocaleString();
card.appendChild(value);
card.appendChild(document.createTextNode(kind.label));
card.addEventListener('click', () => {
const filter = document.getElementById('compareChangeFilter');
filter.value = filter.value === kind.key ? 'all' : kind.key;
filterCompareChanges();
});
cards.appendChild(card);
});
container.appendChild(cards);
// Only issue types whose count moved; unchanged ones are noise here
const movedIssues = (data.issue_changes || []).filter(change => change.delta !== 0);
if (movedIssues.length) {
const wrap = document.createElement('div');
wrap.className = 'compare-issues';
const table = document.createElement('table');
const head = table.createTHead().insertRow();
['Issue', 'Type', 'Previous', 'Current', 'Change'].forEach(label => {
const th = document.createElement('th');
th.textContent = label;
head.appendChild(th);
});
const body = table.createTBody();
movedIssues.forEach(change => {
const row = body.insertRow();
[change.issue, change.type, change.previous, change.current].forEach(value => {
row.insertCell().textContent = value;
});
const delta = row.insertCell();
delta.textContent = change.delta > 0 ? `+${change.delta}` : String(change.delta);
if (change.delta > 0) delta.className = 'compare-delta-up';
else if (change.delta < 0) delta.className = 'compare-delta-down';
});
wrap.appendChild(table);
container.appendChild(wrap);
}
}
function filterCompareChanges() {
const scroller = virtualScrollers.compare;
const empty = document.getElementById('compareEmptyState');
if (!scroller) return;
if (!compareResult) {
scroller.setData([]);
return;
}
compareKindFilter = document.getElementById('compareChangeFilter').value;
const query = document.getElementById('compareSearch').value.trim().toLowerCase();
let rows = compareResult.changes;
if (compareKindFilter !== 'all') {
rows = rows.filter(c => c.change === compareKindFilter);
}
if (query) {
rows = rows.filter(c =>
c.url.toLowerCase().includes(query) ||
String(c.previous).toLowerCase().includes(query) ||
String(c.current).toLowerCase().includes(query));
}
document.querySelectorAll('#compareSummary .compare-card[data-kind]').forEach(card => {
card.classList.toggle('active', card.dataset.kind === compareKindFilter);
});
if (empty) {
empty.style.display = rows.length ? 'none' : 'flex';
const title = empty.querySelector('h3');
const text = empty.querySelector('p');
if (title) title.textContent = 'No Changes';
if (text) text.textContent = compareResult.total_changes
? 'Nothing matches the current filter.'
: 'These two crawls match on every compared field.';
}
scroller.setData(rows);
}
function exportCompareCsv() {
if (!compareState.previousId || !compareState.currentId) {
showNotification('Run a comparison first', 'warning');
return;
}
const params = new URLSearchParams({
previous: compareState.previousId,
current: compareState.currentId,
format: 'csv'
});
window.location.href = '/api/crawls/compare?' + params.toString();
}
function renderCompareRow(row, change) {
const urlCell = makeTextCell(change.url, 'break-all');
urlCell.title = change.url;
row.appendChild(urlCell);
row.appendChild(makeTextCell(compareLabels[change.change] || change.change));
const previous = makeTextCell(change.previous, 'break-word');
previous.title = change.previous;
row.appendChild(previous);
const current = makeTextCell(change.current, 'break-word');
current.title = change.current;
row.appendChild(current);
}
function isIssuesTabActive() {
const issuesTab = document.getElementById('issues-tab');
return issuesTab && issuesTab.classList.contains('active');
@@ -1768,6 +2043,17 @@ function clearAllTables() {
if (virtualScrollers.ngrams) {
virtualScrollers.ngrams.clear();
}
// A new crawl changes the "current" side, so a shown diff is stale
compareResult = null;
compareState.previousId = null;
if (virtualScrollers.compare) {
virtualScrollers.compare.clear();
}
const compareSummary = document.getElementById('compareSummary');
if (compareSummary) compareSummary.innerHTML = '';
const compareStatus = document.getElementById('compareStatus');
if (compareStatus) compareStatus.textContent = '';
const ngramEmpty = document.getElementById('ngramsEmptyState');
if (ngramEmpty) ngramEmpty.style.display = 'block';
@@ -1857,6 +2143,10 @@ function switchTab(tabName) {
loadNgrams();
}
if (tabName === 'compare') {
loadCompareOptions();
}
// Load pending issues data if switching to Issues tab
if (tabName === 'issues' && crawlState.pendingIssues) {
updateIssuesTable(crawlState.pendingIssues);
@@ -2055,6 +2345,10 @@ function filterVirtualScrollerData(scrollerName, filterType) {
return (url.content_type || '').toLowerCase().includes('javascript');
case 'images':
return (url.content_type || '').toLowerCase().includes('image');
case 'indexable':
return url.indexability === 'Indexable';
case 'non_indexable':
return url.indexability === 'Non-Indexable';
default:
return true;
}
@@ -2109,7 +2403,9 @@ function updateFilterCounts() {
html: 0,
css: 0,
js: 0,
images: 0
images: 0,
indexable: 0,
non_indexable: 0
};
crawlState.urls.forEach(url => {
@@ -2134,6 +2430,9 @@ function updateFilterCounts() {
else if (contentType.includes('css')) counts.css++;
else if (contentType.includes('javascript')) counts.js++;
else if (contentType.includes('image')) counts.images++;
if (url.indexability === 'Indexable') counts.indexable++;
else if (url.indexability === 'Non-Indexable') counts.non_indexable++;
});
// Update DOM
@@ -2191,6 +2490,10 @@ function updateStatusCodesTable(filterType = null) {
filteredUrls = filteredUrls.filter(url => (url.content_type || '').includes('javascript'));
} else if (filterType === 'images') {
filteredUrls = filteredUrls.filter(url => (url.content_type || '').includes('image'));
} else if (filterType === 'indexable') {
filteredUrls = filteredUrls.filter(url => url.indexability === 'Indexable');
} else if (filterType === 'non_indexable') {
filteredUrls = filteredUrls.filter(url => url.indexability === 'Non-Indexable');
}
let totalUrls = filteredUrls.length;
@@ -2614,7 +2917,39 @@ function showUrlDetails(url) {
<div><strong>Charset:</strong> ${safeCharset}</div>
<div><strong>Canonical URL:</strong> ${safeCanonical}</div>
<div><strong>Robots Meta:</strong> ${safeRobots}</div>
${urlData.h1_count > 1 ? `<div><strong>H1 Count:</strong> ${urlData.h1_count}</div>` : ''}
${urlData.title_count > 1 ? `<div><strong>Title Tags:</strong> ${urlData.title_count}</div>` : ''}
${urlData.canonical_header ? `<div><strong>Canonical (Link header):</strong> ${escapeHtml(urlData.canonical_header)}</div>` : ''}
</div>
${urlData.canonical_count > 1 ? `
<div class="details-subsection">
<h5>${urlData.canonical_count} canonical declarations:</h5>
${(urlData.canonicals || []).map(href =>
`<div style="word-break: break-all;">${escapeHtml(href) || '<span style="color:#9ca3af">(empty href)</span>'}</div>`
).join('')}
</div>
` : ''}
</div>
<div class="details-section">
<h4>🧭 Indexability</h4>
<div class="details-grid">
<div><strong>Indexability:</strong> ${escapeHtml(urlData.indexability) || 'N/A'}${urlData.indexability_status ? ' (' + escapeHtml(urlData.indexability_status) + ')' : ''}</div>
<div><strong>X-Robots-Tag:</strong> ${escapeHtml(urlData.x_robots_tag) || 'N/A'}</div>
<div><strong>Unique Inlinks:</strong> ${inlinkCount(urlData) ?? 'N/A'}</div>
<div><strong>Internal Outlinks:</strong> ${typeof urlData.outlinks === 'number' ? urlData.outlinks : 'N/A'}</div>
<div><strong>Link Score:</strong> ${typeof urlData.link_score === 'number' ? urlData.link_score + ' / 100' : 'N/A'}</div>
<div><strong>In Sitemap:</strong> ${urlData.in_sitemap === true ? 'Yes' : urlData.in_sitemap === false ? 'No' : 'No sitemap found'}</div>
</div>
${(urlData.redirects && urlData.redirects.length) ? `
<div class="details-subsection">
<h5>Redirect chain (${urlData.redirects.length} hop${urlData.redirects.length !== 1 ? 's' : ''}):</h5>
${urlData.redirects.map(hop =>
`<div style="word-break: break-all;">${escapeHtml(String(hop.status_code || '3xx'))} ${escapeHtml(hop.url)}</div>`
).join('')}
<div style="word-break: break-all;">→ ${escapeHtml(urlData.redirected_to || '')} (${escapeHtml(String(urlData.status_code))})</div>
</div>
` : ''}
</div>
<div class="details-section">
+11
View File
@@ -62,6 +62,17 @@ class IncrementalPoller {
changed.urls = true;
break;
}
case 'url_patch': {
// End-of-crawl analysis: only the changed fields of a
// row already sent. A fresh object, so code holding the
// old row (sorted copies, open details) sees no mutation.
const i = this.urlIndex.get(d.url);
if (i !== undefined) {
this.allUrls[i] = Object.assign({}, this.allUrls[i], d);
changed.urls = true;
}
break;
}
case 'link':
case 'link_update': {
const key = d.source_url + '|' + d.target_url;
+93
View File
@@ -155,6 +155,20 @@
</div>
</div>
</div>
<div class="filter-group">
<div class="filter-header">Indexability</div>
<div class="filter-subgroup">
<div class="filter-item" onclick="toggleFilter('indexable')" title="Internal URLs that return 200 with no noindex and a self-referencing (or no) canonical">
<span class="filter-name">Indexable</span>
<span class="filter-count" id="indexable-count">0</span>
</div>
<div class="filter-item" onclick="toggleFilter('non_indexable')" title="Redirected, error, blocked by robots.txt, noindex (meta or X-Robots-Tag) or canonicalised">
<span class="filter-name">Non-Indexable</span>
<span class="filter-count" id="non_indexable-count">0</span>
</div>
</div>
</div>
</div>
</div>
@@ -215,6 +229,7 @@
<button class="tab-btn" onclick="switchTab('issues')">Issues</button>
<button class="tab-btn" onclick="switchTab('extraction')">Custom Extraction</button>
<button class="tab-btn" onclick="switchTab('ngrams')">N-Grams</button>
<button class="tab-btn" onclick="switchTab('compare')">Compare</button>
<button class="tab-btn" onclick="switchTab('pagespeed')">PageSpeed</button>
<button class="tab-btn" onclick="switchTab('visualization')">Visualization</button>
</div>
@@ -239,6 +254,11 @@
<th>Links (Int/Ext)</th>
<th>Images</th>
<th>JS</th>
<th>Indexability</th>
<th>Indexability Status</th>
<th>Inlinks</th>
<th>Link Score</th>
<th>In Sitemap</th>
<th>Details</th>
</tr>
</thead>
@@ -259,6 +279,9 @@
<th>Content Type</th>
<th>Size</th>
<th>Title</th>
<th>Indexability</th>
<th>Inlinks</th>
<th>Link Score</th>
</tr>
</thead>
<tbody id="internalTableBody">
@@ -487,6 +510,44 @@
</div>
</div>
<div id="compare-tab" class="tab-pane">
<div class="filter-bar compare-bar">
<label class="compare-label">
Compare the current crawl with
<select id="compareCrawlSelect" class="compare-input"></select>
</label>
<button class="compare-btn compare-btn-primary" onclick="runCompare()">Compare</button>
<select id="compareChangeFilter" class="compare-input" onchange="filterCompareChanges()">
<option value="all">All changes</option>
</select>
<input id="compareSearch" class="compare-input" type="text" placeholder="Search URL or value" oninput="filterCompareChanges()">
<button class="compare-btn" onclick="exportCompareCsv()">Export CSV</button>
<span id="compareStatus" class="compare-status"></span>
</div>
<div id="compareSummary" class="compare-summary"></div>
<div class="table-container">
<table class="data-table" id="compareTable">
<thead>
<tr>
<th style="width: 40%;">URL</th>
<th style="width: 16%;">Change</th>
<th style="width: 22%;">Previous</th>
<th style="width: 22%;">Current</th>
</tr>
</thead>
<tbody id="compareTableBody">
<!-- Changes will be populated here -->
</tbody>
</table>
<div class="empty-state" id="compareEmptyState">
<div class="empty-state-content">
<h3>Compare Crawls</h3>
<p>Pick an earlier crawl of this site to see new and removed URLs, status, indexability, title, meta and H1 changes, and issues that appeared or were fixed.</p>
</div>
</div>
</div>
</div>
<div id="pagespeed-tab" class="tab-pane">
<div class="pagespeed-container">
<div class="pagespeed-header">
@@ -888,6 +949,38 @@
<input type="checkbox" name="exportFields" value="robots">
Robots Meta
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="x_robots_tag">
X-Robots-Tag Header
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="indexability">
Indexability
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="indexability_status">
Indexability Status
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="inlinks">
Unique Inlinks
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="outlinks">
Unique Internal Outlinks
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="link_score">
Link Score
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="in_sitemap">
In Sitemap
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="h1_count">
H1 Count
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="custom_extraction">
Custom Extraction (one column per extractor)