Skip to content

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(images): judge image format by what is served, not the URL extension

SigurdWattd9dd36637591
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 03041f3..e5e4df2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Image format is judged by what the server sends, not the URL extension
+ (#331). `parse_html.py --probe-images` fetches each image with a browser
+ `Accept` header and adds `served_format`, `served_bytes`, `negotiated` and
+ `probe_error` to every image entry. `seo-images` and `seo-page` now flag
+ "Wrong Format" only from `served_format`, so a `.jpg` URL that a WebP plugin,
+ Cloudflare Polish or an image CDN already serves as WebP is no longer told to
+ "convert to WebP".
+
## [2.4.1] - 2026-09-29
Google-currency patch. Every changed fact was re-checked against its
diff --git a/scripts/parse_html.py b/scripts/parse_html.py
index 8c411c5..fa9ff0b 100755
--- a/scripts/parse_html.py
+++ b/scripts/parse_html.py
@@ -5,6 +5,7 @@ Parse HTML and extract SEO-relevant elements.
Usage:
python parse_html.py page.html
python parse_html.py --url https://example.com
+ python parse_html.py --url https://example.com --probe-images --json
"""
import argparse
@@ -30,7 +31,8 @@ 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 decode_response_text, safe_requests_get # noqa: E402, I001
+import requests # noqa: E402 (url_safety already hard-requires it)
+from url_safety import URLSafetyError, 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
@@ -44,6 +46,116 @@ _PERFMATTERS_CLASSES = {"perfmatters-lazy", "perfmatters-lazy-loaded"}
_EWWW_CLASSES = {"lazyload-eio", "lazyloaded-eio"}
_GENERIC_LAZY_CLASSES = {"lazyload", "lazyloaded", "lazy", "lazy-loaded"}
+# Served-format probe (issue #331). WordPress WebP plugins (EWWW, ShortPixel,
+# WebP Express, Imagify), Cloudflare Polish and image CDNs serve WebP or AVIF
+# from a `.jpg`/`.png` URL when the browser's Accept header allows it, so the
+# URL extension is not the format visitors receive. The probe asks the way a
+# browser does and reads the format from Content-Type, then the magic bytes.
+IMAGE_ACCEPT = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"
+_SNIFF_BYTES = 32
+_CONTENT_TYPE_FORMATS = {
+ "image/avif": "avif",
+ "image/webp": "webp",
+ "image/jpeg": "jpeg",
+ "image/jpg": "jpeg",
+ "image/pjpeg": "jpeg",
+ "image/png": "png",
+ "image/apng": "png",
+ "image/gif": "gif",
+ "image/svg+xml": "svg",
+ "image/jxl": "jxl",
+}
+
+
+def _sniff_image_format(head: bytes) -> Optional[str]:
+ """Return the image format named by the file's magic bytes, or None."""
+ if head.startswith(b"\xff\xd8\xff"):
+ return "jpeg"
+ if head.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "png"
+ if head.startswith((b"GIF87a", b"GIF89a")):
+ return "gif"
+ if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
+ return "webp"
+ if head[4:8] == b"ftyp" and head[8:12] in (b"avif", b"avis"):
+ return "avif"
+ if head.startswith((b"\xff\x0a", b"\x00\x00\x00\x0cJXL ")):
+ return "jxl"
+ if head.lstrip().startswith((b"<svg", b"<?xml")):
+ return "svg"
+ return None
+
+
+def probe_image_format(src: str, timeout: int = 15) -> dict:
+ """Fetch the start of an image the way a browser does and report what is served.
+
+ Returns ``served_format`` (from the magic bytes, else Content-Type),
+ ``served_bytes`` (Content-Length, or None when the server omits it),
+ ``negotiated`` (True when the response varies on Accept, so the format
+ depends on the client) and ``probe_error`` (None on success).
+ """
+ result = {
+ "served_format": None,
+ "served_bytes": None,
+ "negotiated": False,
+ "probe_error": None,
+ }
+ if not src or urlparse(src).scheme not in ("http", "https"):
+ result["probe_error"] = "not an http(s) URL"
+ return result
+
+ try:
+ resp = safe_requests_get(
+ src,
+ timeout=timeout,
+ allow_redirects=True,
+ stream=True,
+ headers={"Accept": IMAGE_ACCEPT, "Accept-Encoding": "identity"},
+ )
+ try:
+ if resp.status_code >= 400:
+ result["probe_error"] = f"HTTP {resp.status_code}"
+ return result
+ head = next(resp.iter_content(_SNIFF_BYTES), b"")
+ content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
+ result["served_format"] = (
+ _sniff_image_format(head) or _CONTENT_TYPE_FORMATS.get(content_type)
+ )
+ length = resp.headers.get("Content-Length")
+ result["served_bytes"] = int(length) if length and length.isdigit() else None
+ vary = resp.headers.get("Vary", "").lower()
+ result["negotiated"] = "accept" in [v.strip() for v in vary.split(",")]
+ finally:
+ resp.close()
+ except URLSafetyError as exc:
+ result["probe_error"] = f"url_safety: {exc}"
+ except requests.exceptions.RequestException as exc:
+ result["probe_error"] = f"request failed: {exc}"
+ return result
+
+
+def probe_images(images: list, timeout: int = 15, limit: int = 50) -> list:
+ """Add the served-format fields from ``probe_image_format`` to each image entry.
+
+ Probes at most ``limit`` distinct URLs; entries past the limit get
+ ``probe_error`` set so the report never guesses their format.
+ """
+ cache: dict = {}
+ for image in images:
+ src = image.get("src", "")
+ if src not in cache:
+ if len(cache) >= limit:
+ cache[src] = {
+ "served_format": None,
+ "served_bytes": None,
+ "negotiated": False,
+ "probe_error": f"skipped: probe limit of {limit} images reached",
+ }
+ else:
+ cache[src] = probe_image_format(src, timeout=timeout)
+ image.update(cache[src])
+ return images
+
def _has_rel_token(tag, token: str) -> bool:
"""Case-insensitively check whether a tag's ``rel`` attribute carries ``token``.
@@ -253,6 +365,11 @@ def main():
parser.add_argument("file", nargs="?", help="HTML file to parse")
parser.add_argument("--url", "-u", help="Base URL for resolving links")
parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+ parser.add_argument(
+ "--probe-images",
+ action="store_true",
+ help="Fetch each image as a browser would and record the format actually served",
+ )
args = parser.parse_args()
@@ -271,6 +388,8 @@ def main():
args.url = resp.url
result = parse_html(html, args.url)
+ if args.probe_images:
+ probe_images(result["images"])
if args.json:
print(json.dumps(result, indent=2))
diff --git a/skills/seo-images/SKILL.md b/skills/seo-images/SKILL.md
index 80efbee..a63f2f1 100644
--- a/skills/seo-images/SKILL.md
+++ b/skills/seo-images/SKILL.md
@@ -59,6 +59,26 @@ Recommend compression to target thresholds where possible without quality loss.
Recommend WebP/AVIF over JPEG/PNG. Check for `<picture>` element with format fallbacks.
+#### Judge the served format, not the URL extension
+
+Many sites serve WebP or AVIF from a `.jpg`/`.png` URL when the browser asks for it (WordPress WebP
+plugins such as EWWW, ShortPixel, WebP Express and Imagify, Cloudflare Polish, image CDNs). The extension
+is not the format visitors receive. Run
+`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run parse_html.py --url <url> --probe-images --json`,
+which fetches each image with a browser `Accept` header and adds to every image entry:
+
+| Field | Meaning |
+|---|---|
+| `served_format` | Format actually served (`webp`, `avif`, `jpeg`, `png`, `gif`, `svg`, `jxl`), from the magic bytes |
+| `served_bytes` | Size actually served (Content-Length), or `null` when the server omits it |
+| `negotiated` | `true` when the response has `Vary: Accept`, so the format depends on the browser |
+| `probe_error` | Why the image could not be checked, else `null` |
+
+- Flag "Wrong Format" and size savings only from `served_format` / `served_bytes`. A `.jpg` URL with
+ `served_format: webp` is already optimized: do not recommend converting it.
+- If `probe_error` is set, report the format as unverified. Never infer it from the extension.
+- Never suggest a replacement image URL (e.g. `photo.webp`) without confirming it returns HTTP 200.
+
#### Recommended `<picture>` Element Pattern
Use progressive enhancement with the most efficient format first:
@@ -430,7 +450,7 @@ For maximum image SEO, run this pipeline on each image:
|----------|--------|
| URL unreachable | Report connection error with status code. Suggest verifying URL and checking if site requires authentication. |
| No images found on page | Report that no `<img>` elements were detected. Suggest checking if images are loaded via JavaScript or CSS background-image. |
-| Images behind CDN or authentication | Note that image files could not be directly accessed for size analysis. Report available metadata (alt text, dimensions, format from markup) and flag inaccessible resources. |
+| Images behind CDN or authentication | Note that image files could not be directly accessed for size analysis. Report available metadata (alt text, dimensions) and flag inaccessible resources. Mark their format as unverified: the URL extension is not the served format. |
| exiftool not installed | Fall back to ImageMagick for metadata. Recommend: `sudo apt install libimage-exiftool-perl` |
| cwebp not installed | Fall back to ImageMagick or FFmpeg for WebP conversion. Recommend: `sudo apt install webp` |
| DataForSEO MCP not available | Skip Image SERP Analysis section. Note extension is not installed. |
diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.md
index d370398..2bd3180 100644
--- a/skills/seo-page/SKILL.md
+++ b/skills/seo-page/SKILL.md
@@ -55,7 +55,10 @@ metadata:
### Images
- Alt text: present, descriptive, includes keywords where natural
- File size: flag >200KB (warning), >500KB (critical)
-- Format: recommend WebP/AVIF over JPEG/PNG
+- Format: recommend WebP/AVIF over JPEG/PNG, judged by the format actually served, not the URL extension
+ (a `.jpg` URL often serves WebP). Run
+ `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run parse_html.py --url <url> --probe-images --json` and read
+ `served_format` / `served_bytes` per image; see `seo-images` for the rules
- Dimensions: width/height set for CLS prevention
- Lazy loading: report `lazy_method` per image (native | perfmatters | ewww | js-generic | none). Do not flag "not lazy-loaded" when JS lazy-loaders (Perfmatters, EWWW, lazysizes) are detected, they intentionally strip the native `loading="lazy"` attribute and use `data-src` placeholders
diff --git a/tests/test_image_format_probe.py b/tests/test_image_format_probe.py
new file mode 100644
index 0000000..592442c
--- /dev/null
+++ b/tests/test_image_format_probe.py
@@ -0,0 +1,167 @@
+"""
+Tests for the served-format probe in scripts/parse_html.py.
+
+Background: closes issue #331. Sites that negotiate image formats (WordPress
+WebP plugins, Cloudflare Polish, image CDNs) serve WebP or AVIF from a
+`.jpg`/`.png` URL, so judging format by the URL extension produced false
+"convert to WebP" recommendations. The probe reads the served format instead.
+"""
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO_ROOT / "scripts"))
+
+pytest.importorskip("bs4")
+pytest.importorskip("requests")
+import parse_html # noqa: E402
+from parse_html import ( # noqa: E402
+ IMAGE_ACCEPT,
+ _sniff_image_format,
+ probe_image_format,
+ probe_images,
+)
+
+JPEG = b"\xff\xd8\xff\xdb\x00\x84" + b"\x00" * 26
+WEBP = b"RIFF\x20\x40\x00\x00WEBPVP8 " + b"\x00" * 16
+AVIF = b"\x00\x00\x00\x1cftypavif" + b"\x00" * 20
+
+
+class _FakeResponse:
+ def __init__(self, body: bytes, headers: dict, status_code: int = 200):
+ self._body = body
+ self.headers = headers
+ self.status_code = status_code
+ self.closed = False
+
+ def iter_content(self, chunk_size):
+ yield self._body[:chunk_size]
+
+ def close(self):
+ self.closed = True
+
+
+def fake_get(monkeypatch):
+ """Patch safe_requests_get; record each call and return the queued response."""
+ calls = []
+ responses = {}
+
+ def _get(url, **kwargs):
+ calls.append((url, kwargs))
+ return responses[url]
+
+ monkeypatch.setattr(parse_html, "safe_requests_get", _get)
+ return calls, responses
+
+
+ "head, expected",
+ [
+ (JPEG, "jpeg"),
+ (WEBP, "webp"),
+ (AVIF, "avif"),
+ (b"\x89PNG\r\n\x1a\n" + b"\x00" * 8, "png"),
+ (b"GIF89a" + b"\x00" * 8, "gif"),
+ (b"<svg xmlns='http://www.w3.org/2000/svg'>", "svg"),
+ (b"not an image", None),
+ ],
+)
+def test_sniff_image_format(head, expected):
+ assert _sniff_image_format(head) == expected
+
+
+def test_jpeg_url_serving_webp_reports_webp(fake_get):
+ calls, responses = fake_get
+ url = "https://example.com/uploads/photo.jpeg"
+ responses[url] = _FakeResponse(
+ WEBP, {"Content-Type": "image/webp", "Content-Length": "16424", "Vary": "Accept, Accept-Encoding"}
+ )
+
+ result = probe_image_format(url)
+
+ assert result == {
+ "served_format": "webp",
+ "served_bytes": 16424,
+ "negotiated": True,
+ "probe_error": None,
+ }
+ assert calls[0][1]["headers"]["Accept"] == IMAGE_ACCEPT
+ assert responses[url].closed
+
+
+def test_magic_bytes_win_over_a_wrong_content_type(fake_get):
+ _, responses = fake_get
+ url = "https://example.com/photo.png"
+ responses[url] = _FakeResponse(AVIF, {"Content-Type": "image/png"})
+
+ result = probe_image_format(url)
+
+ assert result["served_format"] == "avif"
+ assert result["served_bytes"] is None
+ assert result["negotiated"] is False
+
+
+def test_content_type_used_when_bytes_are_unknown(fake_get):
+ _, responses = fake_get
+ url = "https://example.com/photo.jpg"
+ responses[url] = _FakeResponse(b"\x00" * 32, {"Content-Type": "image/jpeg; charset=binary"})
+
+ assert probe_image_format(url)["served_format"] == "jpeg"
+
+
+def test_http_error_is_reported_not_guessed(fake_get):
+ _, responses = fake_get
+ url = "https://example.com/missing.webp"
+ responses[url] = _FakeResponse(b"<html>", {"Content-Type": "text/html"}, status_code=404)
+
+ result = probe_image_format(url)
+
+ assert result["served_format"] is None
+ assert result["probe_error"] == "HTTP 404"
+
+
+def test_data_uri_is_not_fetched(fake_get):
+ calls, _ = fake_get
+
+ result = probe_image_format("data:image/svg+xml;base64,PHN2Zz4=")
+
+ assert result["probe_error"] == "not an http(s) URL"
+ assert calls == []
+
+
+def test_url_safety_rejection_is_reported(monkeypatch):
+ def _blocked(url, **kwargs):
+ raise parse_html.URLSafetyError("blocked private IP")
+
+ monkeypatch.setattr(parse_html, "safe_requests_get", _blocked)
+
+ result = probe_image_format("https://internal.example/photo.jpg")
+
+ assert result["served_format"] is None
+ assert result["probe_error"].startswith("url_safety:")
+
+
+def test_probe_images_dedupes_and_respects_limit(fake_get):
+ calls, responses = fake_get
+ a, b = "https://example.com/a.jpg", "https://example.com/b.jpg"
+ responses[a] = _FakeResponse(WEBP, {"Content-Type": "image/webp"})
+ images = [{"src": a}, {"src": a}, {"src": b}]
+
+ probe_images(images, limit=1)
+
+ assert len(calls) == 1
+ assert images[0]["served_format"] == images[1]["served_format"] == "webp"
+ assert images[2]["served_format"] is None
+ assert "probe limit" in images[2]["probe_error"]
+
+
+def test_parse_html_alone_makes_no_requests(fake_get):
+ calls, _ = fake_get
+
+ result = parse_html.parse_html('<img src="photo.jpg" alt="x">', "https://example.com/")
+
+ assert calls == []
+ assert "served_format" not in result["images"][0]