<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Tomi Šeregi — Engineering Notes]]></title><description><![CDATA[Practical tutorials on MCP, AI integrations, Python and web quality, with reproducible examples and honest engineering limitations.]]></description><link>https://tomiseregi.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/63542569b29017d65cd63702/76d24f61-6a48-447b-bb0a-c4304701c9c4.png</url><title>Tomi Šeregi — Engineering Notes</title><link>https://tomiseregi.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 12:46:31 GMT</lastBuildDate><atom:link href="https://tomiseregi.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Catch canonical and robots meta regressions before deploying]]></title><description><![CDATA[Build a Python regression checker for canonical URLs and robots meta directives, with 20 tested fixtures and explicit route-level expectations.]]></description><link>https://tomiseregi.hashnode.dev/catch-canonical-and-robots-meta-regressions-before-deploying</link><guid isPermaLink="true">https://tomiseregi.hashnode.dev/catch-canonical-and-robots-meta-regressions-before-deploying</guid><category><![CDATA[Python]]></category><category><![CDATA[Testing]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Tomi Šeregi]]></dc:creator><pubDate>Tue, 24 Nov 2026 16:22:05 GMT</pubDate><content:encoded><![CDATA[<p>A successful HTTP response does not prove that a page has the metadata your application intended to ship. A template change can add an unexpected robots directive, duplicate a canonical declaration, or silently change the preferred URL of a filtered page.</p>
<p>Canonical annotations express a preference about which URL should represent duplicate or similar content. A <code>noindex</code> directive asks supporting search crawlers not to index a page, provided they can access the directive. Neither a canonical nor <code>noindex</code> is an access-control mechanism.</p>
<p>This tutorial uses a deliberately bounded Python checker to compare HTML metadata with explicit route-level expectations. It works offline, uses only the standard library, and makes no claim about actual search-engine indexation.</p>
<h2>Define the expected state, not a generic SEO score</h2>
<p>An independently indexable documentation route might be expected to have a self-referencing canonical and no generic <code>noindex</code>. A filtered page may intentionally canonicalize to another route. Some pages intentionally omit canonical annotations or use <code>noindex</code>. Encode those choices in a test rather than treating every difference from a self-canonical as an error.</p>
<p>An important detail: checking only whether a target differs from the current URL misses regressions between two different non-self canonical targets. Comparing with the exact expected URL catches that drift.</p>
<h2>Implement the checker</h2>
<p>Save the complete example below as <code>check_metadata.py</code>. It expects well-formed, generated HTML with an explicit head. It collects canonical annotations and simple comma-separated generic robots directives, resolves relative canonical URLs against the supplied page URL, rejects several unsupported URL forms, and asks for manual review when a base href is present.</p>
<pre><code class="language-python">from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit


class HeadMetadata(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_head = False
        self.seen_head = False
        self.has_base = False
        self.canonicals = []
        self.robots = set()

    def handle_starttag(self, tag, attrs):
        if tag == 'head':
            self.in_head = self.seen_head = True
        if not self.in_head:
            return
        attrs = dict(attrs)
        if tag == 'base' and 'href' in attrs:
            self.has_base = True
        rel = (attrs.get('rel') or '').lower().split()
        if tag == 'link' and 'canonical' in rel:
            self.canonicals.append((attrs.get('href') or '').strip())
        if tag == 'meta' and (attrs.get('name') or '').lower() == 'robots':
            self.robots.update(
                part.strip().lower()
                for part in (attrs.get('content') or '').split(',')
            )

    def handle_endtag(self, tag):
        if tag == 'head':
            self.in_head = False


def check(html, page_url, expected_canonical, *, expected_noindex=False):
    meta = HeadMetadata()
    meta.feed(html)
    meta.close()
    if not meta.seen_head:
        return ['explicit head not found']
    if meta.has_base:
        return ['base href unsupported; review manually']

    findings = []
    if len(meta.canonicals) &gt; 1:
        findings.append('multiple canonical declarations')
    targets = []
    for href in meta.canonicals:
        if not href:
            findings.append('empty canonical href')
            continue
        try:
            target = urljoin(page_url, href)
            parts = urlsplit(target)
            if (parts.scheme not in ('http', 'https') or not parts.hostname
                    or parts.username is not None or parts.fragment
                    or any(ch.isspace() for ch in href)):
                raise ValueError('unsupported canonical URL')
            _ = parts.port  # Raises ValueError for an invalid port.
        except ValueError:
            findings.append('unsupported canonical href')
            continue
        targets.append(target)

    if expected_canonical is None:
        if meta.canonicals:
            findings.append('unexpected canonical declaration')
    elif not targets:
        findings.append('expected canonical target missing')
    elif any(t != expected_canonical for t in targets):
        findings.append('canonical target differs from expected URL')

    noindex = bool(meta.robots &amp; {'noindex', 'none'})
    if noindex != expected_noindex:
        findings.append('robots noindex state differs from expectation')
    return findings


if __name__ == '__main__':
    url = 'https://example.com/docs/'
    archive = 'https://example.com/archive/'
    link = '&lt;link rel="canonical" href="/docs/"&gt;'
    fixtures = [
        ('self canonical', link, url, False, []),
        ('absolute', f'&lt;link rel="canonical" href="{url}"&gt;', url, False, []),
        ('case and whitespace', '&lt;LINK REL="CANONICAL" HREF=" /docs/ "&gt;', url, False, []),
        ('unexpected noindex', link + '&lt;meta name="robots" content="noindex, follow"&gt;', url, False, ['robots noindex state differs from expectation']),
        ('intentional noindex', link + '&lt;meta name="robots" content="NOINDEX, follow"&gt;', url, True, []),
        ('missing noindex', link, url, True, ['robots noindex state differs from expectation']),
        ('none', link + '&lt;meta name="robots" content="none"&gt;', url, True, []),
        ('duplicate', link + link, url, False, ['multiple canonical declarations']),
        ('empty', '&lt;link rel="canonical" href=""&gt;', url, False, ['empty canonical href', 'expected canonical target missing']),
        ('missing', '', url, False, ['expected canonical target missing']),
        ('intentionally absent', '', None, False, []),
        ('unexpected canonical', link, None, False, ['unexpected canonical declaration']),
        ('intentional alternate', '&lt;link rel="canonical" href="/archive/"&gt;', archive, False, []),
        ('alternate drift', '&lt;link rel="canonical" href="/other/"&gt;', archive, False, ['canonical target differs from expected URL']),
        ('base', '&lt;base href="/elsewhere/"&gt;' + link, url, False, ['base href unsupported; review manually']),
        ('unsupported scheme', '&lt;link rel="canonical" href="javascript:alert(1)"&gt;', url, False, ['unsupported canonical href', 'expected canonical target missing']),
        ('malformed host', '&lt;link rel="canonical" href="https://[broken"&gt;', url, False, ['unsupported canonical href', 'expected canonical target missing']),
        ('comment ignored', link + '&lt;!-- &lt;meta name="robots" content="noindex"&gt; --&gt;', url, False, []),
        ('multiple robots tags', link + '&lt;meta name="robots" content="index"&gt;&lt;meta name="robots" content="noindex"&gt;', url, True, []),
    ]
    for name, fragment, canonical, noindex, expected in fixtures:
        html = f'&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;{fragment}&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;'
        result = check(html, url, canonical, expected_noindex=noindex)
        if result != expected:
            raise AssertionError((name, result, expected))
    # Also ensure that body-only metadata does not count as head metadata.
    html = f'&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;{link}&lt;/body&gt;&lt;/html&gt;'
    if check(html, url, url) != ['expected canonical target missing']:
        raise AssertionError('body-only canonical')
    print(f'{len(fixtures) + 1}/{len(fixtures) + 1} fixture checks passed')
</code></pre>
<h2>Run the tests</h2>
<pre><code class="language-sh">python check_metadata.py
python -O check_metadata.py
</code></pre>
<p>Both commands were run against this exact example during the article audit. Each returned:</p>
<pre><code class="language-text">20/20 fixture checks passed
</code></pre>
<p>The fixtures cover intended and unintended canonical targets, duplicate and empty annotations, intentional absence, expected and unexpected noindex, malformed URLs, base href, comments, conflicting robots directives, and body-only metadata. They are synthetic tests, not observations from a production site. Explicit exceptions keep the checks active even when Python is run with optimization enabled.</p>
<h2>Apply it to your build</h2>
<p>Once your build generates the HTML, load the output for a representative route. Supply the intended public URL and its expected canonical and noindex state. For example, a documentation page might use its own URL, while an intentionally consolidated archive route might use a different expected canonical. Pass <code>None</code> only when your policy expects no canonical declaration.</p>
<pre><code class="language-python">from pathlib import Path
from check_metadata import check

url = 'https://example.com/docs/'
html = Path('dist/docs/index.html').read_text(encoding='utf-8')
findings = check(html, url, url, expected_noindex=False)
if findings:
    raise SystemExit('\n'.join(findings))
</code></pre>
<p>Keep a small manifest of representative routes and their expected states in version control. Fail the build on unexpected changes and review any intentional policy change alongside the template modification. The sample build path above is illustrative; adapt it to your framework.</p>
<h2>Know the limits</h2>
<p>This is a regression check for a narrow HTML contract, not a full validator or crawler. Python's HTMLParser is not a browser DOM parser; malformed markup, implicit head elements, inert template content and unusual nesting can produce different results. The checker handles simple comma-separated robots directives, not arbitrary directive grammars. It does not assess crawler-specific directives, robots.txt, HTTP Link or X-Robots-Tag headers, redirects, response status, client-side rendering, or actual canonical selection. URL comparison is intentionally literal after relative resolution; it does not establish semantic URL equivalence. The example rejects a few unsupported URL forms but is not a comprehensive URL validator.</p>
<p>Use browser and HTTP-level checks when you need those additional guarantees. Google treats canonical annotations as signals rather than promises, and a noindex directive does not protect private content. The value here is a small, reproducible guardrail before deployment.</p>
<h2>References</h2>
<ul>
<li><a href="https://docs.python.org/3/library/html.parser.html">Python: HTMLParser</a></li>
<li><a href="https://docs.python.org/3/library/urllib.parse.html">Python: urllib.parse</a></li>
<li><a href="https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls">Google Search Central: canonical URLs</a></li>
<li><a href="https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag">Google Search Central: robots meta directives and HTTP headers</a></li>
</ul>
<p><strong>AI disclosure:</strong> This article and example were generated and technically audited with ChatGPT. The 20 synthetic fixture checks were executed locally in normal and optimized Python mode. No production results or independent human review are claimed.</p>
]]></content:encoded></item></channel></rss>