BYTESLIP ← Back
Knowledge Base // Tutorial 120

Audit Titles, Meta Descriptions, Canonicals and Broken Links With One Python Script

Difficulty: Medium ~30 min Python · Termux

Online crawlers cap free scans and need your site live. This script reads the files on disk, before you upload, and checks every page for title and description length, duplicates, canonical URLs, <h1> count, lang, noindex, images missing alt, broken JSON-LD and internal links that point nowhere. It uses only the Python standard library, so it runs in Termux on a phone or tablet.

Folder to audit report Four tiles: site folder, seo_audit.py, CSV report, fix and re-run. SITE FOLDER SEO_AUDIT .PY SEO-AUDIT .CSV FIX + RE-RUN
Safety // Read First

Warnings

ImportantThe 65 and 155 character limits in the script are a house style, not a Google rule. Google says there’s no limit on title or meta description length; results are just cut to fit the screen. The script also only knows the files in the folder you give it. Links to files that live only on the server (downloads, tools) will show as broken.

Checklist // Before You Start

What You Need

How this was tested: Ran with Python 3.13 and 3.14 on Linux, first on a fixture site with planted errors. It caught all of them: an 87-character title, a missing description, a canonical missing its trailing slash, two <h1> tags, no lang, noindex, an image without alt, a JSON-LD trailing comma, two broken links, and a duplicate title and description. Then we ran it on a 163-page mirror of a live static site with --clean. All “broken” links it reported were files outside the mirror, and each one returned HTTP 200 on the live site.

Walkthrough // Steps 01–06

Install → get the folder → save → run → fix → repeat

One command per run. The report opens in any spreadsheet app.

  1. Step 1: Install Python

    pkg install python
    python3 --version
  2. Step 2: Get your site folder onto the device

    If the only copy is on the server: in cPanel File Manager, select public_html → Compress → Zip Archive → then Download the zip. cPanel’s docs note that Compress only works if Zip is installed on the server. Unzip it in Termux:

    cd ~/storage/downloads
    unzip public_html.zip -d site
  3. Step 3: Save the script

    Save this as seo_audit.py (for example with nano ~/seo_audit.py):

    #!/usr/bin/env python3
    """seo_audit.py - check a static site folder before you upload it (Byteslip).
    Usage: python3 seo_audit.py SITE_DIR https://example.com [--clean]
      --clean  your server hides .html (about.html is served as /about)
    Checks every .html file: title, meta description, canonical, one <h1>,
    html lang, noindex, img alt, JSON-LD syntax, and internal links that
    point at files that do not exist. Writes seo-audit.csv. Stdlib only."""
    import csv, json, os, sys
    from collections import defaultdict
    from html.parser import HTMLParser
    from urllib.parse import urljoin, urlparse, unquote
    
    TITLE_MAX, DESC_MAX = 65, 155   # house style, not Google limits
    
    class Page(HTMLParser):
        def __init__(self):
            super().__init__()
            self.title = ""; self.in_title = False; self.titles = 0
            self.desc = None; self.canonical = None; self.lang = None
            self.robots = ""; self.h1 = 0; self.links = []
            self.img_no_alt = 0; self.jsonld = []; self.in_ld = False; self.buf = ""
        def handle_starttag(self, tag, attrs):
            a = {k: (v or "") for k, v in attrs}
            if tag == "html": self.lang = a.get("lang")
            elif tag == "title":   # first <title> only; inline <svg> can have its own
                self.titles += 1; self.in_title = self.titles == 1
            elif tag == "meta":
                n = a.get("name", "").lower()
                if n == "description": self.desc = a.get("content", "")
                if n == "robots": self.robots = a.get("content", "").lower()
            elif tag == "link" and "canonical" in a.get("rel", "").lower().split():
                self.canonical = a.get("href")
            elif tag == "h1": self.h1 += 1
            elif tag == "a" and a.get("href"): self.links.append(a["href"])
            elif tag == "img" and "alt" not in a: self.img_no_alt += 1
            elif tag == "script" and a.get("type", "").lower() == "application/ld+json":
                self.in_ld = True; self.buf = ""
        def handle_endtag(self, tag):
            if tag == "title": self.in_title = False
            if tag == "script" and self.in_ld:
                self.in_ld = False; self.jsonld.append(self.buf)
        def handle_data(self, data):
            if self.in_title: self.title += data
            if self.in_ld: self.buf += data
    
    CLEAN = "--clean" in sys.argv
    
    def url_for(root, path, base):
        rel = os.path.relpath(path, root).replace(os.sep, "/")
        if rel == "index.html": rel = ""
        elif rel.endswith("/index.html"): rel = rel[:-len("index.html")]
        elif CLEAN and rel.endswith(".html"): rel = rel[:-5]
        return base.rstrip("/") + "/" + rel
    
    def exists(root, href_path):
        p = os.path.join(root, unquote(href_path).lstrip("/"))
        if href_path.endswith("/"): return os.path.isfile(os.path.join(p, "index.html"))
        return os.path.isfile(p) or os.path.isfile(p + ".html") or os.path.isfile(os.path.join(p, "index.html"))
    
    def main(root, base):
        host = urlparse(base).netloc
        rows, titles, descs = [], defaultdict(list), defaultdict(list)
        for d, _, files in os.walk(root):
            for f in sorted(files):
                if not f.endswith(".html"): continue
                path = os.path.join(d, f)
                p = Page(); p.feed(open(path, encoding="utf-8", errors="replace").read())
                url = url_for(root, path, base); probs = []
                t = " ".join(p.title.split())
                if not t: probs.append("missing <title>")
                elif len(t) > TITLE_MAX: probs.append(f"title {len(t)} chars")
                if p.desc is None: probs.append("missing meta description")
                elif len(p.desc) > DESC_MAX: probs.append(f"description {len(p.desc)} chars")
                if not p.canonical: probs.append("missing canonical")
                elif p.canonical != url: probs.append(f"canonical is {p.canonical}")
                if p.h1 != 1: probs.append(f"{p.h1} <h1> tags")
                if not p.lang: probs.append("missing <html lang>")
                if "noindex" in p.robots: probs.append("noindex")
                if p.img_no_alt: probs.append(f"{p.img_no_alt} <img> without alt")
                for i, block in enumerate(p.jsonld, 1):
                    try: json.loads(block)
                    except ValueError as e: probs.append(f"JSON-LD block {i} invalid: {e}")
                for href in p.links:
                    u = urlparse(urljoin(url, href))
                    if u.scheme in ("http", "https") and u.netloc == host and u.path and not exists(root, u.path):
                        probs.append(f"broken link {href}")
                if t: titles[t].append(url)
                if p.desc: descs[p.desc].append(url)
                rows.append([url, len(t), len(p.desc or ""), "; ".join(probs)])
        for label, seen in (("title", titles), ("description", descs)):
            for text, urls in seen.items():
                if len(urls) > 1:
                    for r in rows:
                        if r[0] in urls: r[3] = (r[3] + "; " if r[3] else "") + f"duplicate {label}"
        with open("seo-audit.csv", "w", newline="", encoding="utf-8") as fh:
            w = csv.writer(fh); w.writerow(["url", "title_len", "desc_len", "problems"]); w.writerows(sorted(rows))
        bad = [r for r in rows if r[3]]
        for r in sorted(bad): print(f"{r[0]}\n  -> {r[3]}")
        print(f"\n{len(rows)} pages checked, {len(bad)} with problems. Full list: seo-audit.csv")
        return 1 if bad else 0
    
    if __name__ == "__main__":
        args = [a for a in sys.argv[1:] if a != "--clean"]
        if len(args) != 2: sys.exit(__doc__)
        sys.exit(main(args[0], args[1]))
  4. Step 4: Run it

    python3 ~/seo_audit.py site/public_html https://example.com --clean

    Each problem page is printed with its list of issues, followed by a summary like 163 pages checked, 12 with problems. The full table is in seo-audit.csv in the folder you ran it from. It exits with code 1 if anything was found, which is handy in scripts.

    The script works out each page’s URL from its file path: tutorials/x/index.html becomes /tutorials/x/. It expects each canonical to match exactly, so a missing trailing slash shows up.

  5. Step 5: Fix in order of impact

    • broken link: fix or remove the link. Inside a site, one wrong path can strand a page.
    • canonical is …: point the canonical at the page’s own final URL. See Title, Meta Description, Canonical and Open Graph Tags.
    • noindex: make sure it’s intentional. Google won’t show those pages.
    • duplicate title / description: Google recommends a unique, descriptive title for each page.
    • title N chars: shorten it if the important words are at the end, where results get cut off.
    • JSON-LD block invalid: the error gives the line and column. See Add JSON-LD Structured Data to a Static Site.
  6. Step 6: Run it before every upload

    Make it a habit: edit → run → upload. To check just the pages you changed, point it at a folder that holds only those pages (links to other pages will show as broken there, so ignore those). Change TITLE_MAX or DESC_MAX at the top if your house style is different.

Pro Tip

Sort the CSV by problem

Questions // FAQ

FAQ

Why not just use Search Console?

Search Console shows what Google already crawled, days later. This script runs on your files before upload, so mistakes never go live. Use both.

How long should titles and descriptions be?

Google sets no limit and cuts results to fit the screen. The script uses 65 and 155 characters as a house style so the key words are likely to show. Choose your own numbers and use them on every page.

Does it check external links?

No. It only checks links on your own domain against files in the folder, so it’s fast and works offline.

Can it read pages that need JavaScript?

No. It reads the HTML as written, which is also what most crawlers see first on a static site.

Keep Reading
Sources // Verified

Official docs

No length limit, truncation, and unique titles: Influencing your title links and Control your snippets. Canonical URLs: How to specify a canonical URL. noindex: Block Search indexing with noindex. Alt text: Google image SEO best practices. Compress and Download: cPanel File Manager. Parser: Python html.parser.

← All Tutorials Byteslip Apps