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.
| Check | What the script looks for | Typical result |
|---|---|---|
| Return tag | Page A points to page B, but page B does not point back to A | The language versions do not connect |
| x-default | The cluster has no x-default entry | The default page for unmatched users becomes unclear |
| Target availability | A linked URL is not among the crawled pages | A 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:
- Does the page contain an x-default entry? If not, it belongs to a cluster but the default destination stays unclear.
- Is every linked target among the crawled pages? If not, the address may contain a typo or point to a removed or redirected page.
- 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:
- Run the script against a sitemap from a test or staging environment and save the output.
- Group the return tag lines by language pair and find the pattern that repeats most often.
- Fix template or configuration causes in one pass, then run the script again.
- 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.




No comments yet
Leave a Comment