BYTESLIP ← Back
Knowledge Base // Tutorial 124

Find Orphan Pages, Deep Pages and Weak Anchor Text With a Python Link Map

Difficulty: Medium ~30 min Python · HTML · Termux

Google’s SEO Starter Guide says the vast majority of new pages Google finds every day are found through links. On a hand-built site, a new page is only linked where you remember to add a link. This script reads your site folder and maps every internal link. It shows pages nothing links to, pages buried many clicks from the home page, vague link text like “read more”, and links Google can’t follow.

Site folder to a fixed link map Five tiles: site folder, link graph, orphans and depth, anchor text, relink. SITE FOLDER LINK GRAPH ORPHANS + DEPTH ANCHOR TEXT RELINK
Safety // Read First

Warnings

ImportantThe script reads the HTML files as written. Links that JavaScript adds after the page loads aren’t in the map. Google says those can still be crawled if they’re real <a href> elements, so check them in URL Inspection’s rendered HTML. The 3-click limit is a house rule, not a Google rule. Google says there’s no magic number of links per page.

Checklist // Before You Start

What You Need

How this was tested: Ran with Python 3.13 and 3.12 on a test site with planted problems: a page reachable only through an onclick, two pages that only link to each other, a chain five clicks deep, a “read more” link, an image link with empty alt, and a javascript: link. It reported every one. An empty link with a title attribute wasn’t flagged, because Google uses the title as anchor text in that case. On a 163-page copy of a live static site, it mapped 956 internal links: no orphans, nothing deeper than 3 clicks, 4 image links with no alt text, and several guides linked from only one page.

Walkthrough // Steps 01–07

Rules → folder → script → run → fix → re-run

Runs offline on the files you’re about to upload.

  1. Step 1: Know what Google can follow

    From Google’s link best practices:

    • Google can generally only crawl a link if it’s an <a> element with an href. An onclick on an <a href> is fine; an onclick with no href isn’t reliable.
    • The link text tells people and Google what the target is about. Google lists “click here”, “read more”, “website” and “article” as too generic.
    • For an image link, Google uses the image’s alt as the anchor text. If a link is empty, Google can fall back to its title attribute.
    • Every page you care about should have a link from at least one other page on your site.
  2. Step 2: Get your site folder

    Run the script on the same files you upload. If the only copy is on the server, download a zip of public_html from cPanel File Manager and unzip it, as shown in the audit guide. The script skips 404.html, since nothing should link to it.

  3. Step 3: Save the script

    Save this as link_graph.py. It turns each file into its URL (tutorials/x/index.html becomes /tutorials/x/). It accepts links written as /about when the file is about.html. Then it walks the links from the home page.

    #!/usr/bin/env python3
    """Map internal links in a static site folder: orphans, click depth, weak anchors.
    
    Usage: python3 link_graph.py SITE_FOLDER [MAX_DEPTH]
    Run it on the folder you upload (the one with your home index.html).
    """
    import collections, os, re, sys
    from html.parser import HTMLParser
    from urllib.parse import urljoin, urlsplit
    
    WEAK = {"click here", "here", "read more", "more", "learn more", "this", "link", "this page"}
    
    class Links(HTMLParser):
        def __init__(self):
            super().__init__()
            self.links, self.fake, self._href, self._text = [], 0, None, []
        def handle_starttag(self, tag, attrs):
            a = dict(attrs)
            if tag == "a":
                href = a.get("href")
                if href is None or href.strip().lower().startswith("javascript:"):
                    self.fake += 1
                self._href, self._text, self._title = href, [], a.get("title") or ""
            elif tag == "img" and self._href is not None:
                self._text.append(a.get("alt") or "")
            elif "onclick" in a and "location" in (a.get("onclick") or ""):
                self.fake += 1
        def handle_data(self, data):
            if self._href is not None:
                self._text.append(data)
        def handle_endtag(self, tag):
            if tag == "a" and self._href is not None:
                text = " ".join(" ".join(self._text).split()) or self._title.strip()
                self.links.append((self._href, text))
                self._href = None
    
    def page_url(root, path):
        rel = os.path.relpath(path, root).replace(os.sep, "/")
        if rel == "index.html":
            return "/"
        if rel.endswith("/index.html"):
            return "/" + rel[:-len("index.html")]
        return "/" + rel
    
    def resolve(href, base, pages):
        url = urljoin("https://site.invalid" + base, href)
        parts = urlsplit(url)
        if parts.netloc != "site.invalid":
            return None
        p = parts.path or "/"
        for cand in (p, p + "/", p + ".html", p.rstrip("/") + ".html"):
            if cand in pages:
                return cand
        return None
    
    def main():
        if len(sys.argv) < 2:
            sys.exit(__doc__)
        root = sys.argv[1]
        max_depth = int(sys.argv[2]) if len(sys.argv) > 2 else 3
        files = {}
        for d, _, names in os.walk(root):
            for n in names:
                if n.endswith(".html") and n != "404.html":
                    files[page_url(root, os.path.join(d, n))] = os.path.join(d, n)
        inbound = collections.defaultdict(set)
        out = {}
        weak, fake = [], {}
        for url, path in files.items():
            p = Links()
            p.feed(open(path, encoding="utf-8", errors="replace").read())
            out[url] = set()
            if p.fake:
                fake[url] = p.fake
            for href, text in p.links:
                target = resolve(href, url, files)
                if target and target != url:
                    out[url].add(target)
                    inbound[target].add(url)
                    if text.lower().strip(" .!→>»") in WEAK or not text:
                        weak.append((url, text or "(no text or alt)", target))
        depth = {"/": 0} if "/" in files else {}
        queue = collections.deque(depth)
        while queue:
            u = queue.popleft()
            for v in sorted(out.get(u, ())):
                if v not in depth:
                    depth[v] = depth[u] + 1
                    queue.append(v)
        print(f"Pages: {len(files)}   internal links: {sum(len(v) for v in out.values())}")
        orphans = sorted(u for u in files if u != "/" and not inbound[u])
        print(f"\nOrphans (no links from any other page): {len(orphans)}")
        for u in orphans:
            print("  ", u)
        unreachable = sorted(u for u in files if u not in depth and u not in orphans)
        print(f"\nLinked, but not reachable from the home page: {len(unreachable)}")
        for u in unreachable:
            print("  ", u)
        deep = sorted((d, u) for u, d in depth.items() if d > max_depth)
        print(f"\nMore than {max_depth} clicks from home: {len(deep)}")
        for d, u in deep:
            print(f"   {d}  {u}")
        print("\nFewest inbound links (top 10):")
        for u in sorted((u for u in files if u != "/" and inbound[u]), key=lambda u: len(inbound[u]))[:10]:
            print(f"   {len(inbound[u]):3}  {u}")
        print(f"\nWeak anchor text: {len(weak)}")
        for src, text, dst in weak[:30]:
            print(f'   "{text}" on {src} -> {dst}')
        print(f"\nLinks Google can't follow (<a> without href, javascript:, onclick): {sum(fake.values())}")
        for u, n in sorted(fake.items()):
            print(f"   {n:3}  {u}")
    
    if __name__ == "__main__":
        main()
  4. Step 4: Run it

    python3 ~/link_graph.py site/public_html

    Add a number to change the depth limit, for example python3 ~/link_graph.py site/public_html 4. Output from our test site:

    Pages: 11   internal links: 13
    
    Orphans (no links from any other page): 1
       /guides/c/
    
    Linked, but not reachable from the home page: 2
       /island/one/
       /island/two/
    
    More than 3 clicks from home: 2
       4  /guides/a/part-2/part-3/
       5  /guides/a/part-2/part-3/part-4/
    
    Fewest inbound links (top 10):
         1  /island/two/
         1  /island/one/
         1  /guides/a/
         1  /guides/a/part-2/
         1  /guides/a/part-2/part-3/
         1  /guides/a/part-2/part-3/part-4/
         2  /about.html
         2  /guides/
         2  /guides/b/
    
    Weak anchor text: 2
       "read more" on /guides/ -> /guides/b/
       "(no text or alt)" on /guides/a/ -> /guides/b/
    
    Links Google can't follow (<a> without href, javascript:, onclick): 2
         2  /guides/
  5. Step 5: Give every orphan and island page a parent

    Orphans have no links from any other page, so only your sitemap can lead Google to them. Islands, like /island/one/ and /island/two/ above, link to each other, but nothing that starts from the home page reaches them. For both, add a link from the matching hub page and from one or two related pages, using text that describes the target. If a page shouldn’t exist any more, remove it and let it return 404 or 410 (see Custom 404 Pages).

  6. Step 6: Bring deep pages closer and add breadcrumbs

    Chains like part-2 → part-3 → part-4 put the last page many clicks away. Add a contents list on the first page that links to every part, and link the series from its hub. A visible breadcrumb trail on each page (Home / Tutorials / Hub / Page) gives every page links back up the tree. Google can also show breadcrumbs from BreadcrumbList markup; see Add JSON-LD Structured Data to a Static Site.

  7. Step 7: Rewrite weak anchors and unfollowable links, then re-run

    • “read more” / “click here”: name the target, for example <a href="/tutorials/termux-cron-jobs/">schedule scripts with Termux cron</a>. Google’s tip: read only the link text, out of context, and check it still makes sense.
    • (no text or alt): add an alt that describes where the link goes. Good alt text helps screen reader users too; see Accessible, Semantic HTML.
    • Links Google can’t follow: change <span onclick="location.href=..."> or href="javascript:..." into a plain <a href="/path/">.

    Run the script again. The counts should drop to zero, except for anything you’ve chosen to keep.

Pro Tip

Link new pages from old ones

Questions // FAQ

FAQ

Isn’t a sitemap enough?

A sitemap helps Google find URLs, but Google’s link guidance says every page you care about should have a link from at least one other page on your site. Do both.

How many internal links should a page have?

Google says there’s no magic number, and that if it feels like too many, it probably is. Link where it helps the reader.

Should internal links be nofollow?

Google’s link docs describe nofollow for links you don’t trust, paid links and links users add. None of those apply to links between your own pages.

Does it find broken links?

Not directly; links to files that don’t exist are skipped. The audit script in Audit Titles, Meta and Broken Links With Python reports them.

Keep Reading
Sources // Verified

Official docs

Crawlable links, anchor text, title and alt fallbacks, internal linking and nofollow: Link best practices for Google. How Google finds new pages: SEO Starter Guide. Breadcrumbs: Breadcrumb structured data. Script modules: html.parser and urllib.parse.

← All Tutorials Byteslip Apps