Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
fix(fetch): decode every fetched page like fetch_page does (#314)
Agrici Danielb1f90cca5d61
diff --git a/scripts/fetch_page.py b/scripts/fetch_page.pyindex a931edd..c9c7274 100755--- a/scripts/fetch_page.py+++ b/scripts/fetch_page.py@@ -19,7 +19,6 @@ from __future__ import annotationsimport argparseimport jsonimport os-import reimport sysfrom typing import Optional@@ -35,6 +34,7 @@ if _SCRIPTS_DIR not in sys.path:from url_safety import ( # noqa: E402DEFAULT_REQUEST_HEADERS,URLSafetyError,+ decode_response_text,safe_requests_session,validate_url_strict,)@@ -59,53 +59,9 @@ GOOGLEBOT_USER_AGENT = (# English variant, which corrupts hreflang and international audits.DEFAULT_HEADERS = dict(DEFAULT_REQUEST_HEADERS)-_CONTENT_TYPE_CHARSET_RE = re.compile(r"charset\s*=\s*['\"]?([^;,'\"\s>]+)", re.IGNORECASE)-_META_CHARSET_RE = re.compile(- r"<meta[^>]+charset\s*=\s*['\"]?([^;,'\"\s/>]+)",- re.IGNORECASE,-)-_BOMS = (- (b"\xef\xbb\xbf", "utf-8-sig"),- (b"\xff\xfe", "utf-16-le"),- (b"\xfe\xff", "utf-16-be"),-)---def _decode_bytes(raw: bytes, encoding: str) -> str:- try:- return raw.decode(encoding, errors="replace")- except LookupError:- return raw.decode("utf-8", errors="replace")---def _extract_charset_from_content_type(content_type: str) -> str | None:- match = _CONTENT_TYPE_CHARSET_RE.search(content_type or "")- return match.group(1).strip() if match else None---def _extract_meta_charset(raw: bytes) -> str | None:- head = raw[:4096].decode("ascii", errors="ignore")- match = _META_CHARSET_RE.search(head)- return match.group(1).strip() if match else None---def _decode_response_content(response) -> str:- """Decode HTTP bytes deterministically for stable SEO snapshots."""- raw = response.content or b""- for marker, encoding in _BOMS:- if raw.startswith(marker):- return _decode_bytes(raw, encoding)-- content_type = response.headers.get("Content-Type", "") if response.headers else ""- charset = _extract_charset_from_content_type(content_type)- if charset:- return _decode_bytes(raw, charset)-- charset = _extract_meta_charset(raw)- if charset:- return _decode_bytes(raw, charset)-- return raw.decode("utf-8", errors="replace")+# Response decoding lives in url_safety (decode_response_text) so every script+# that fetches through the safe helpers decodes the same way (issue #314).+_decode_response_content = decode_response_textdef fetch_page(diff --git a/scripts/gbp_deprecation_lint.py b/scripts/gbp_deprecation_lint.pyindex 5ea8710..f6fa638 100755--- a/scripts/gbp_deprecation_lint.py+++ b/scripts/gbp_deprecation_lint.py@@ -35,7 +35,7 @@ from pathlib import Path_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)-from url_safety import URLSafetyError, safe_requests_get # noqa: E402+from url_safety import URLSafetyError, decode_response_text, safe_requests_get # noqa: E402# Patterns for retired GBP chat. The "Message" / "Chat" CTAs alone are# common on commercial sites — we only flag when they appear NEAR a@@ -110,7 +110,7 @@ def main() -> int:else:try:resp = safe_requests_get(args.source, timeout=20)- html = resp.text+ html = decode_response_text(resp)except URLSafetyError as exc:print(f"Error: url_safety: {exc}", file=sys.stderr)return 2diff --git a/scripts/nlp_analyze.py b/scripts/nlp_analyze.pyindex e8d5ca7..f09937b 100644--- a/scripts/nlp_analyze.py+++ b/scripts/nlp_analyze.py@@ -30,7 +30,7 @@ try:redact_google_api_key,validate_url,)- from url_safety import URLSafetyError, safe_requests_get+ from url_safety import URLSafetyError, decode_response_text, safe_requests_getexcept ImportError:import ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))@@ -40,7 +40,7 @@ except ImportError:redact_google_api_key,validate_url,)- from url_safety import URLSafetyError, safe_requests_get+ from url_safety import URLSafetyError, decode_response_text, safe_requests_getNLP_ENDPOINT = "https://language.googleapis.com/v2/documents:annotateText"NLP_V1_ENTITIES_ENDPOINT = "https://language.googleapis.com/v1/documents:analyzeEntities"@@ -264,7 +264,7 @@ def analyze_url(headers={"User-Agent": "Mozilla/5.0 (compatible; ClaudeSEO/1.7 NLP Analyzer)"},)resp.raise_for_status()- html = resp.text+ html = decode_response_text(resp)except URLSafetyError as e:return {"error": f"URL blocked by SSRF protection: {e}"}except requests.exceptions.RequestException as e:diff --git a/scripts/parasite_risk.py b/scripts/parasite_risk.pyindex a9a78f8..13b2410 100755--- a/scripts/parasite_risk.py+++ b/scripts/parasite_risk.py@@ -55,7 +55,7 @@ from urllib.parse import urlparse_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)-from url_safety import URLSafetyError, safe_requests_get # noqa: E402+from url_safety import URLSafetyError, decode_response_text, safe_requests_get # noqa: E402# Indicators of third-party authored content. Each adds 1 hit per page._THIRD_PARTY_BYLINE_PATTERNS = (@@ -179,7 +179,7 @@ def scan(urls: Iterable[str], *, timeout: int = 20) -> dict:for url in urls:try:resp = safe_requests_get(url, timeout=timeout, allow_redirects=True)- rows.append(_audit_page(resp.url, resp.text))+ rows.append(_audit_page(resp.url, decode_response_text(resp)))except URLSafetyError as exc:errors.append({"url": url, "error": f"url_safety: {exc}"})except Exception as exc: # noqa: BLE001 — surface every transport errordiff --git a/scripts/parse_html.py b/scripts/parse_html.pyindex 78ae77e..5010b61 100755--- a/scripts/parse_html.py+++ b/scripts/parse_html.py@@ -30,7 +30,7 @@ except ImportError:_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)-from url_safety import safe_requests_get # noqa: E402, I001+from url_safety import decode_response_text, safe_requests_get # noqa: E402, I001# Lazy-loader detection — covers native + the major JS lazy-loaders found on# WordPress/WooCommerce sites (Perfmatters, EWWW Image Optimizer, generic@@ -267,7 +267,7 @@ def main():html = sys.stdin.read()if not html and args.url:resp = safe_requests_get(args.url, timeout=30, allow_redirects=True)- html = resp.text+ html = decode_response_text(resp)args.url = resp.urlresult = parse_html(html, args.url)diff --git a/scripts/preload_check.py b/scripts/preload_check.pyindex d3c77f2..645aab9 100644--- a/scripts/preload_check.py+++ b/scripts/preload_check.py@@ -66,7 +66,7 @@ from typing import Optional_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)-from url_safety import URLSafetyError, safe_requests_get # noqa: E402+from url_safety import URLSafetyError, decode_response_text, safe_requests_get # noqa: E402_SPECULATION_BLOCK_RE = re.compile(r'<script\b[^>]*\btype\s*=\s*["\']speculationrules["\'][^>]*>(?P<body>.*?)</script>',@@ -217,7 +217,7 @@ def main() -> int:print(f"Error: url_safety: {exc}", file=sys.stderr)return 2- result = {"url": resp.url, **analyse(resp.text, dict(resp.headers))}+ result = {"url": resp.url, **analyse(decode_response_text(resp), dict(resp.headers))}if args.json:json.dump(result, sys.stdout, indent=2)diff --git a/scripts/render_page.py b/scripts/render_page.pyindex 8869d30..b62f4e1 100644--- a/scripts/render_page.py+++ b/scripts/render_page.py@@ -105,6 +105,7 @@ if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)from url_safety import ( # noqa: E402 (sys.path massage above is intentional)URLSafetyError,+ decode_response_text,make_safe_playwright_route_handler,safe_requests_get,validate_url_strict,@@ -458,7 +459,7 @@ def render_page(# Step 1 — raw fetch (always; needed for SPA detection and as a baseline).try:resp = safe_requests_get(norm_url, timeout=30, allow_redirects=True)- result["raw_content"] = resp.text+ result["raw_content"] = decode_response_text(resp)if resp.history:result["redirect_chain"] = [{"url": r.url, "status_code": r.status_code} for r in resp.historydiff --git a/scripts/ucp_check.py b/scripts/ucp_check.pyindex 241cf26..be2621f 100644--- a/scripts/ucp_check.py+++ b/scripts/ucp_check.py@@ -42,6 +42,7 @@ if _SCRIPTS_DIR not in sys.path:sys.path.insert(0, _SCRIPTS_DIR)from url_safety import ( # noqa: E402URLSafetyError,+ decode_response_text,safe_requests_get,validate_url_strict,)@@ -192,7 +193,7 @@ def audit_site(report["summary"] = f"http-{resp.status_code} on discovery"return reportreport["profile_present"] = True- parsed = parse_profile(resp.text)+ parsed = parse_profile(decode_response_text(resp))report["parse"] = parsedif probe_endpoints and parsed.get("capabilities"):diff --git a/scripts/url_safety.py b/scripts/url_safety.pyindex 730679c..f01c127 100644--- a/scripts/url_safety.py+++ b/scripts/url_safety.py@@ -781,6 +781,62 @@ DEFAULT_REQUEST_HEADERS = {}+_CONTENT_TYPE_CHARSET_RE = re.compile(r"charset\s*=\s*['\"]?([^;,'\"\s>]+)", re.IGNORECASE)+_META_CHARSET_RE = re.compile(+ r"<meta[^>]+charset\s*=\s*['\"]?([^;,'\"\s/>]+)",+ re.IGNORECASE,+)+_BOMS = (+ (b"\xef\xbb\xbf", "utf-8-sig"),+ (b"\xff\xfe", "utf-16-le"),+ (b"\xfe\xff", "utf-16-be"),+)+++def _decode_bytes(raw: bytes, encoding: str) -> str:+ try:+ return raw.decode(encoding, errors="replace")+ except LookupError:+ return raw.decode("utf-8", errors="replace")+++def _extract_charset_from_content_type(content_type: str) -> str | None:+ match = _CONTENT_TYPE_CHARSET_RE.search(content_type or "")+ return match.group(1).strip() if match else None+++def _extract_meta_charset(raw: bytes) -> str | None:+ head = raw[:4096].decode("ascii", errors="ignore")+ match = _META_CHARSET_RE.search(head)+ return match.group(1).strip() if match else None+++def decode_response_text(response) -> str:+ """Decode a response body deterministically: BOM, then the Content-Type+ charset, then ``<meta charset>``, then UTF-8.++ Use this instead of ``response.text``. ``requests`` falls back to+ ISO-8859-1 for text/* responses without a charset, which garbles UTF-8+ pages (issue #314). Reading ``response.content`` consumes a streamed body,+ so streamed callers should decode the bytes they already read.+ """+ raw = response.content or b""+ for marker, encoding in _BOMS:+ if raw.startswith(marker):+ return _decode_bytes(raw, encoding)++ content_type = response.headers.get("Content-Type", "") if response.headers else ""+ charset = _extract_charset_from_content_type(content_type)+ if charset:+ return _decode_bytes(raw, charset)++ charset = _extract_meta_charset(raw)+ if charset:+ return _decode_bytes(raw, charset)++ return raw.decode("utf-8", errors="replace")++def _with_default_headers(kwargs: dict) -> dict:"""Fill in DEFAULT_REQUEST_HEADERS for header keys the caller did not set."""headers = dict(DEFAULT_REQUEST_HEADERS)diff --git a/tests/test_fetch_page_decoding.py b/tests/test_fetch_page_decoding.pyindex 64f888c..e4988ac 100644--- a/tests/test_fetch_page_decoding.py+++ b/tests/test_fetch_page_decoding.py@@ -43,3 +43,44 @@ def test_invalid_bytes_are_replaced_not_dropped() -> None:decoded = fetch_page._decode_response_content(response)assert "valid utf8" in decodedassert "\ufffd" in decoded+++def _real_response(body: bytes, content_type: str):+ """A requests.Response built the way the HTTP adapter builds one."""+ import io++ import requests++ resp = requests.Response()+ resp.status_code = 200+ resp.headers["Content-Type"] = content_type+ resp.raw = io.BytesIO(body)+ resp.encoding = requests.utils.get_encoding_from_headers(resp.headers)+ return resp+++def test_issue_314_bare_text_html_utf8_is_not_decoded_as_latin1():+ from url_safety import decode_response_text++ body = "<html><head><title>Spécialité</title></head></html>".encode()+ assert "Spécialité" in _real_response(body, "text/html").text # the bug+ assert "Spécialité" in decode_response_text(_real_response(body, "text/html"))+++def test_issue_314_explicit_charset_is_still_honoured():+ from url_safety import decode_response_text++ body = "Café".encode("iso-8859-1")+ assert decode_response_text(_real_response(body, "text/html; charset=iso-8859-1")) == "Café"+++def test_issue_314_fetching_scripts_use_the_shared_decoder():+ """Scripts that fetch pages must not fall back to response.text."""+ from pathlib import Path++ scripts = Path(__file__).resolve().parents[1] / "scripts"+ for name in ("render_page.py", "parse_html.py", "nlp_analyze.py", "preload_check.py",+ "parasite_risk.py", "ucp_check.py", "gbp_deprecation_lint.py"):+ text = (scripts / name).read_text(encoding="utf-8")+ assert "decode_response_text(" in text, name+ assert "resp.text" not in text, namediff --git a/tests/test_render_page.py b/tests/test_render_page.pyindex 9031403..7f82d1c 100644--- a/tests/test_render_page.py+++ b/tests/test_render_page.py@@ -284,7 +284,8 @@ def test_render_page_never_mode_against_example_com() -> None:def _fake_response(text: str, status: int = 200, url: str = "https://x.example/"):return SimpleNamespace(- text=text, status_code=status, headers={"Content-Type": "text/html"},+ text=text, content=text.encode("utf-8"), status_code=status,+ headers={"Content-Type": "text/html"},url=url, history=[],)diff --git a/tests/test_technical_depth.py b/tests/test_technical_depth.pyindex 810fc3a..a5f5ebe 100644--- a/tests/test_technical_depth.py+++ b/tests/test_technical_depth.py@@ -185,7 +185,8 @@ _PLAIN_HTML = "<html><head></head><body><p>nothing to preload</p></body></html>"def _run_preload_main(monkeypatch, capsys, *argv: str) -> tuple[int, str]:- response = SimpleNamespace(url="https://example.com/", text=_PLAIN_HTML, headers={})+ response = SimpleNamespace(url="https://example.com/", text=_PLAIN_HTML,+ content=_PLAIN_HTML.encode("utf-8"), headers={})monkeypatch.setattr(preload_check, "safe_requests_get", lambda *a, **k: response)monkeypatch.setattr(sys, "argv", ["preload_check.py", "https://example.com/", *argv])code = preload_check.main()