DELTAWEB
All posts
Technical SEO

Writing an hreflang Checker in Python: A Step-by-Step Guide

Build a short Python script that collects hreflang pairs from your sitemap and page tags, then flags missing return tags and x-default gaps, step by step.

Writing an hreflang Checker in Python: A Step-by-Step Guide
10 minReading time
Arif KuruAuthor

Imagine that a few weeks after launching German, French and Spanish pages on an export website, someone notices that the language versions no longer recognize each other. This is a hypothetical example, but it is a common story: the team decides to check hreflang tags by hand, and opening three hundred product pages one by one takes more than a week. Even then, nobody can tell which German page fails to link back to its English counterpart. In this article we will write a short Python script that collects hreflang pairs from the sitemap and from page tags, then reports missing return tags and x-default gaps. For the concepts behind the code, start with what hreflang is and how it works.

Key Takeaways

  • Hreflang errors are easy to miss by hand. A script that reads the sitemap and page tags can do the same work in minutes.
  • Every hreflang pair must be reciprocal: if page A points to page B, page B must point back to page A (the return tag).
  • The script uses only the Python standard library. No external service, API key or paid tool is required.
  • The script is a review helper. Read its output together with Search Console data and manual checks.

Why put hreflang checks into a script?

On a small site with three languages, checking tags by eye is possible. With six languages, thousands of URLs and new content every week, the number of mistakes quickly exceeds what a person can review. One missing tag on one page can break a whole cluster, because every page in the cluster depends on the others to confirm the relationship.

The goal of the script is to find inconsistencies with your own check, ideally before they go live. Google's hreflang documentation states that language versions should reference each other and that these links must be reciprocal. The script looks at exactly that rule and at a few common gaps.

What the script does not check

The script does not measure content quality, translation accuracy or whether a keyword fits the language. It does not judge whether the language code is the right one for the audience; it only checks structural consistency. For those questions, a broader review such as the international SEO guide on hreflang errors is a better companion.

Which checks will we run?

The script runs three core checks. Each one catches a type of error that appears often in real projects.

CheckWhat the script looks forTypical result
Return tagPage A points to page B, but page B does not point back to AThe language versions do not connect
x-defaultThe cluster has no x-default entryThe default page for unmatched users becomes unclear
Target availabilityA linked URL is not among the crawled pagesA typo, or an old or redirected URL

These three checks are an automated version of the process described in the return tag error detection and fix guide. For terms such as cluster and self-reference, the hreflang glossary is a useful reference.

What a correct three-language cluster looks like

Before reading the script, it helps to see a correct example. The four lines below connect the Turkish, German and English versions of one product, plus the default page. This configuration is hypothetical.

<link rel="alternate" hreflang="tr" href="https://example.com/tr/urun-a" />
<link rel="alternate" hreflang="de" href="https://example.com/de/urun-a" />
<link rel="alternate" hreflang="en" href="https://example.com/en/product-a" />
<link rel="alternate" hreflang="x-default" href="https://example.com/en/product-a" />

Three points matter here. First, every language version lists the whole cluster, including itself. Second, x-default is not a language; it is the page for users whose language or country does not match any listed version. Third, the target addresses are written in full and consistently. A trailing slash or a mix of http and https can create false warnings in any checker.

Preparing the environment

Requirements

Python 3.8 or newer is enough. The script uses only urllib, re and xml.etree.ElementTree, so there is no package to install with pip. The machine that runs the script only needs internet access to your site.

File and configuration

We use a single file called hreflang_check.py. Replace the SITEMAP_URL constant at the top with your own sitemap address. No other configuration is needed.

Step 1: Read the URL list from the sitemap

The sitemap is the first source of pages to check. The sitemap_urls function downloads the sitemap XML, reads every loc element and normalizes the addresses. Normalization here means removing a trailing slash, so that two spellings of the same page are treated as one address. This small detail prevents many false "missing return tag" warnings later.

If the file is a sitemap index, the function returns the child sitemap addresses as if they were pages. They are fetched, but because they carry no hreflang tags they do not appear in the report. The final section explains how to handle large sites with several sitemap files.

Step 2: Read hreflang values from page tags

Every page's HTML contains link rel="alternate" elements. The alternates function finds them with a regular expression, turns their attributes into a dictionary and keeps only the alternate links that have an hreflang attribute. The result maps each language code to a URL, for example tr, de, en and x-default.

This is a deliberate simplification. A regular expression is not a full HTML parser. It works well when hreflang tags are written plainly inside the head element, and the attribute dictionary handles any attribute order. If your tags are injected by JavaScript in the browser, however, this approach is not enough on its own, and the server response must contain the tags.

Step 3: Check return tags and x-default

The check function walks through all pages and asks three questions for each one:

  1. Does the page contain an x-default entry? If not, it belongs to a cluster but the default destination stays unclear.
  2. Is every linked target among the crawled pages? If not, the address may contain a typo or point to a removed or redirected page.
  3. Does the target page point back to this page? If not, the return tag is missing, and a search engine may not treat the pair as reliable.

The return tag check looks for the current URL among the hreflang values of the target page. For that comparison to work, both the page address and the target addresses must be normalized in the same way. The norm function handles this.

Step 4: Run the script and read the report

Run the script with python hreflang_check.py. The output contains one line for each problematic page and ends with the number of pages scanned. The sample output below is hypothetical; example.com is not a real site.

https://example.com/de/urun-a -> return tag yok (https://example.com/en/product-a)
https://example.com/en/product-b -> x-default yok
https://example.com/tr/urun-c -> de: hedef taranmadı (https://example.com/de/urun-c-eski)
128 sayfa tarandı.

Start with the return tag lines, because they usually reveal which language pairs are affected most. Then look at the target not crawled lines; these are often a URL change or a leftover from an old template. The x-default warnings have a lower priority but are usually easy to fix.

Once the fixes are done, add the implementation checklist to your publishing process so that the same patterns do not return.

Common mistakes when running the script

The problems people hit first are usually caused by data rather than code. The list below covers the points to review before trusting the report.

  • Trailing slash differences: If the sitemap includes a trailing slash and the tag does not, the comparison fails. Normalization handles this, but the source should still be consistent.
  • Mixed http and https: Addresses from a staging environment can leak into the cluster. Search the report for these explicitly.
  • Language code format: If your site mixes tr-TR and tr, pick one format and apply it everywhere.
  • Removed pages: A page that has been taken offline but remains in the sitemap makes the return tags of its sister pages look broken.

Full script

The code below combines all four steps in one file. Only the SITEMAP_URL line needs to be changed for your site.

import re
import urllib.request
import xml.etree.ElementTree as ET

SITEMAP_URL = "https://www.example.com/sitemap.xml"  # your sitemap address
SM_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
TAG_RE = re.compile(r"<link\s[^>]*>", re.I)
ATTR_RE = re.compile(r"([\w-]+)\s*=\s*[\"']([^\"']*)[\"']")


def norm(url):
    return url.strip().rstrip("/")


def fetch(url):
    with urllib.request.urlopen(url, timeout=15) as resp:
        return resp.read().decode("utf-8", "replace")


def sitemap_urls(sitemap_url):
    root = ET.fromstring(fetch(sitemap_url).encode("utf-8"))
    return [norm(loc.text) for loc in root.iter(SM_NS + "loc")]


def alternates(html):
    found = {}
    for tag in TAG_RE.findall(html):
        attrs = {k.lower(): v for k, v in ATTR_RE.findall(tag)}
        if attrs.get("rel", "").lower() == "alternate" and "hreflang" in attrs:
            found[attrs["hreflang"].lower()] = norm(attrs.get("href", ""))
    return found


def crawl(urls):
    pages = {}
    for url in urls:
        try:
            pages[url] = alternates(fetch(url))
        except Exception as err:
            print(f"ATLANDI {url}: {err}")
    return pages


def check(pages):
    problems = []
    for url, alts in pages.items():
        if not alts:
            continue
        if "x-default" not in alts:
            problems.append((url, "x-default yok"))
        for lang, target in alts.items():
            if lang == "x-default" or target == url:
                continue
            if target not in pages:
                problems.append((url, f"{lang}: hedef taranmadı ({target})"))
            elif url not in pages[target].values():
                problems.append((url, f"{lang}: return tag yok ({target})"))
    return problems


if __name__ == "__main__":
    pages = crawl(sitemap_urls(SITEMAP_URL))
    for url, message in check(pages):
        print(f"{url} -> {message}")
    print(f"{len(pages)} sayfa tarandı.")

Limits and things to watch

Redirects

The script follows requests with urllib but does not report redirect chains separately. If a sitemap address returns a 301 to another address, the hreflang value in the tag and the sitemap address may differ. The report will show a warning, and you will need to compare the two addresses by hand.

Tags added by JavaScript

The script reads the raw HTML response. If hreflang tags are added in the browser with JavaScript, the script cannot see them. Search engines can process some JavaScript pages, but tags present in the server response are far easier to verify and maintain.

Sitemap indexes and large sites

Sites with several sitemap files should add a small loop that reads each child sitemap from the index. On large sites, running the crawl in batches and adding a short pause between requests keeps the load on your server low and makes the results easier to reproduce.

Self-reference

The script does not verify that a page lists its own language. To confirm that every page includes itself, add a separate check or review this part manually.

Conclusion and next steps

The script we wrote reads hreflang clusters from the sitemap and page tags, then reports missing return tags and x-default gaps. A practical order for the next steps is:

  1. Run the script against a sitemap from a test or staging environment and save the output.
  2. Group the return tag lines by language pair and find the pattern that repeats most often.
  3. Fix template or configuration causes in one pass, then run the script again.
  4. Keep the script as a recurring check in your publishing calendar.

A hreflang cluster is not finished once it is set up. Repeating the same check after every new language or page type is the cheapest way to catch problems before they grow.

FAQ

Frequently Asked Questions

  • Should I write a Python script or use a ready-made hreflang tool?

    Both are valid. Ready-made tools give quick results on small sites. On large or custom-built multilingual sites, your own script lets you tune the rules to your team's needs. The script in this article is best treated as a review helper.

  • Which Python versions does the script support?

    Python 3.8 and newer is enough. The script relies only on the standard library, so no extra packages need to be installed.

  • What is a return tag and why does it matter?

    A return tag is the link a language version uses to point back to the version that points to it. Google's documentation expects these links to be reciprocal. One-way annotations may not be treated as reliable, and the cluster breaks.

  • Is x-default always required?

    According to Google's documentation, x-default is optional. However, setting a default page for users whose language or country matches none of your versions is a common and useful practice. The script reports a missing x-default as a warning.

  • Can the script read sitemap index files?

    Not in its current form. It reads a plain URL set and does not fetch child sitemaps on its own. For large sites, add a loop that reads each sitemap listed in the index file.

  • Does the script detect hreflang tags added by JavaScript?

    No. urllib only retrieves the first HTML response from the server. If tags are added in the browser, you need a browser-based tool, or the tags should be generated on the server side.

  • How often should I run the script?

    Run it after adding a new language, after a large URL change, and at regular intervals as part of your publishing calendar. There is no fixed frequency; it depends on how often your site changes.

  • Will the script slow down my site?

    The script downloads each page once and in sequence. Still, avoid running it during peak traffic, and add a short pause between requests on heavy sites to reduce server load.

Related Articles

No comments yet

Leave a Comment