DEV Community

Usman Ishaq
Usman Ishaq

Posted on

A Python script to audit internal links from a sitemap

Usman Ishaq is a semantic SEO strategist and consultant, and the founder of Digital Vikingz. Internal links are one of the first things he checks on a site, and his website is built so every page is reachable from others. This script automates the first pass of that check.

What does the script report?

It reports three things: how many internal links point to and from each sitemap URL, which sitemap URLs have no inbound link (orphans), and which links use generic anchor text such as "click here" or "read more". It also writes everything to a CSV.

Why these three checks?

An orphan page is listed in the sitemap but no other page links to it, so crawlers and visitors find it only through the sitemap. Inbound counts show which pages the site treats as important. Generic anchors waste the one place where a link can describe its target.

What do you need?

Python 3.9 or newer and three packages:

pip install requests beautifulsoup4 lxml
Enter fullscreen mode Exit fullscreen mode

The script

Save it as link_audit.py.

#!/usr/bin/env python3
"""Audit internal links from a sitemap: python link_audit.py URL [--main]"""
import argparse, csv, time
from collections import defaultdict
from urllib.parse import urljoin, urldefrag, urlparse

import requests
from bs4 import BeautifulSoup

GENERIC = {"click here", "read more", "learn more", "here", "more",
           "this page", "this link", "link", "continue", "details"}
HEADERS = {"User-Agent": "internal-link-audit/1.0"}


def fetch(url):
    r = requests.get(url, headers=HEADERS, timeout=15)
    r.raise_for_status()
    return r


def sitemap_urls(url):
    soup = BeautifulSoup(fetch(url).content, "xml")
    locs = [l.get_text(strip=True) for l in soup.find_all("loc")]
    if soup.find("sitemapindex"):
        return [u for loc in locs for u in sitemap_urls(loc)]
    return locs


def norm(url):
    p = urlparse(urldefrag(url)[0])
    return p._replace(scheme=p.scheme.lower(), netloc=p.netloc.lower(),
                      path=p.path.rstrip("/") or "/", params="", query="").geturl()


def host(url):
    return urlparse(url).netloc.removeprefix("www.")


def label(a):
    text = " ".join(a.get_text(" ", strip=True).lower().split())
    img = a.find("img")
    return text or (img.get("alt", "").strip().lower() if img else "")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("sitemap")
    ap.add_argument("--main", action="store_true",
                    help="only count links inside <main>, ignoring nav and footer")
    ap.add_argument("--delay", type=float, default=0.5)
    ap.add_argument("--out", default="link_audit.csv")
    args = ap.parse_args()

    pages = sorted({norm(u) for u in sitemap_urls(args.sitemap)})
    site = host(args.sitemap)
    inbound, outbound, generic = defaultdict(set), defaultdict(set), []

    for page in pages:
        try:
            r = fetch(page)
        except requests.RequestException as e:
            print(f"SKIP {page}: {e}")
            continue
        if "text/html" not in r.headers.get("content-type", ""):
            continue
        soup = BeautifulSoup(r.text, "lxml")
        root = (soup.find("main") if args.main else None) or soup
        for a in root.find_all("a", href=True):
            href = a["href"].strip()
            if href.startswith(("mailto:", "tel:", "javascript:")):
                continue
            target = norm(urljoin(page, href))
            if host(target) != site or target == page:
                continue
            outbound[page].add(target)
            inbound[target].add(page)
            text = label(a)
            if text in GENERIC or not text:
                generic.append((page, target, text or "(empty)"))
        time.sleep(args.delay)

    orphans = [p for p in pages if not inbound[p]]
    with open(args.out, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["url", "inbound", "outbound", "orphan"])
        for p in pages:
            w.writerow([p, len(inbound[p]), len(outbound[p]), p in orphans])

    print(f"Pages in sitemap: {len(pages)}")
    print(f"Orphan pages: {len(orphans)}")
    for p in orphans:
        print(f"  {p}")
    print(f"Generic anchors: {len(generic)}")
    for page, target, text in generic:
        print(f"  {page} -> {target}  [{text}]")
    print(f"Wrote {args.out}")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

How do you run it?

python link_audit.py https://example.com/sitemap.xml --main
Enter fullscreen mode Exit fullscreen mode

Replace the URL with a site you own or have permission to crawl. Sitemap index files are followed automatically. The --main flag counts only links inside <main>, so a site-wide menu does not give every page an inbound link and hide real orphans.

How should you read the output?

Treat the output as a list of leads, not verdicts. Some limits to keep in mind:

  • Query strings and fragments are dropped, so /page?a=1 and /page count as one URL.
  • Links added by JavaScript after load are not seen, because requests does not run scripts.
  • A page that is meant to be reached only from an ad or an email may be a correct orphan.
  • Redirecting links are counted against the URL written in the href, so fix those separately.

For orphans, decide whether the page should exist, then add a contextual link from a related page. For generic anchors, rewrite the link text to name the target.

If you would like a person to read the findings with you, the semantic content audit covers internal linking alongside the content itself.


Usman Ishaq is a semantic SEO strategist and consultant, and the founder of Digital Vikingz. He plans websites around entities, attributes and values, then builds topical maps, briefs, pages, internal links and schema so businesses rank in Google and get named by ChatGPT, Gemini and Perplexity.

Top comments (1)

Collapse
 
fgrandon profile image
Francisco Grandón •

Scoping the BeautifulSoup scan with --main is a practical touch, since nav and footer links otherwise mask true orphan pages in the inbound counts. Checking empty or generic anchors alongside <img alt> also catches accessibility gaps in the same pass. Have you run into JS-rendered SPAs where requests misses client-side links, and would you add a headless fallback or keep it strictly static?