DEV Community

Nataq Ali
Nataq Ali

Posted on Fully Autonomous

A small Python sitemap audit: check expected canonical URLs before release

A sitemap can be valid XML and still list the wrong URLs. For a release, I like to compare the sitemap against the intended canonical URL list before asking search engines to discover anything.

This small offline check helps developers catch mismatches early. It does not fetch URLs, measure search ranking, or prove indexing.

Inputs

Save the site's sitemap as sitemap.xml and a reviewed list of intended canonical URLs as expected.txt (one absolute URL per line). For this example, both files describe a single HTTPS host.

A reproducible check

from collections import Counter
from pathlib import Path
from urllib.parse import urlsplit
import xml.etree.ElementTree as ET


NS = {'sm': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
HOST = 'example.com'
root = ET.parse('sitemap.xml').getroot()
if root.tag != '{' + NS['sm'] + '}urlset':
    raise ValueError('Expected a urlset, not a sitemap index')
locs = [(node.text or '').strip()
        for node in root.findall('sm:url/sm:loc', NS)]
expected = {line.strip() for line in
            Path('expected.txt').read_text(encoding='utf-8').splitlines()
            if line.strip()}


def eligible(url):
    try:
        p = urlsplit(url)
        return (p.scheme == 'https' and p.hostname == HOST
                and not p.username and not p.password
                and p.port in (None, 443) and not p.fragment)
    except ValueError:
        return False


counts = Counter(locs)
print('Invalid or off-host:', sorted(u for u in counts if not eligible(u)))
print('Duplicates:', sorted(u for u, n in counts.items() if n > 1))
print('Unexpected:', sorted(set(locs) - expected))
print('Missing:', sorted(expected - set(locs)))

Enter fullscreen mode Exit fullscreen mode

Example result

Suppose the intended pages are https://example.com/ and https://example.com/products/widget. If the sitemap instead contains the homepage twice plus https://example.com/products/widget?view=quick, the check flags the duplicated homepage, the unexpected variant and the missing canonical product URL.

Do not automatically remove a URL solely because it has a query string: some parameter URLs are meaningful. Decide which URLs belong in the sitemap by reviewing the site's canonical strategy and actual content.

What to check after deployment

  • Open the live XML and confirm the final URL and exact intended entries.

  • Inspect a representative page's canonical and crawl directives.

  • In an owned Search Console property, check actual index status separately from sitemap processing.

  • If the sitemap reports a temporary fetch error but the live XML loads, log both observations and allow normal processing. Repeated submissions do not establish indexation.

Official reference: Google sitemap guidance.

For the broader workflow, see the search readiness audit resources.

— Nataq Ali, SEO, AEO & GEO Specialist. Professional profile. Original AI-assisted educational example; no client results or indexing guarantees.

Top comments (1)

Collapse
 
alicexixi85 profile image
Dejun (Alice) Chen •

The post-deploy step I'd automate rather than sample: fetch every sitemap URL once and check two things, that it returns 200 without a redirect, and that its rel=canonical points to itself. A sitemap that lists A while A's canonical points to B sends mixed signals, and canonical chains or loops only show up when you follow them across pages, not on one representative page. It's a few lines on top of your script with requests and html.parser.