DEV Community

appierun
appierun

Posted on

Audit Outbound Links Across Your Sitemap with Python (Standard Library Only): Missing rel, rel Typos and Footer Credits

Small business sites collect outbound links the way a kitchen drawer collects takeout menus. A bakery writes a "best stand mixers" post with affiliate links. The owner agrees to a paid post for the local holiday market. A comments section fills up with links, some of them spam. The agency that built the site puts "Website by" in the footer. Nobody looks at the rel attributes on any of it.

If you look after sites for a few local clients, checking this by hand means opening every page and reading the source. This post builds a small Python script (standard library only) that reads a sitemap, collects every link on every page, and flags the outbound links that should carry a rel qualifier and do not.

Disclosure: Appie.run publishes this post. The only Appie mentions are two free tools near the end. Everything else is plain Python you can run yourself. The test site is a fictional local bakery built for this post and served from localhost, and every external domain in it is a made-up .example host that the script never contacts. The Google guidance quoted below is from Google Search Central's "Qualify your outbound links to Google" page and the link spam section of its spam policies, and the noopener note is from MDN. I read all three on 27 Nov 2026.

What Google and MDN say

From Google's Qualify your outbound links to Google page:

  • Regular links need no rel attribute. "For regular links that you expect Google to fetch and parse without any qualifications, you don't need to add a rel attribute."
  • rel="sponsored" is for "links that are advertisements or paid placements." The page adds that nofollow "is still an acceptable way to flag them, though sponsored is preferred."
  • rel="ugc" is recommended for user-generated content links, "such as comments and forum posts."
  • rel="nofollow" is for when the other values don't apply. "For links within your own site, use the robots.txt disallow rule."
  • Multiple values can be "a space- or comma-separated list."

The link spam section of Google's spam policies lists, among its examples, "Exchanging money for links, or posts that contain links," "Widely distributed links in the footers or templates of various sites," and advertorials where payment is received for articles with links that pass ranking credit. It also says buying and selling links for advertising is fine "as long as they are qualified with a rel="nofollow" or rel="sponsored" attribute value."

From MDN on rel="noopener": "Setting target="_blank" on <a>, <area> and <form> elements implicitly provides the same rel behavior as setting rel="noopener"." So a target="_blank" link without noopener is a low-priority note for older browsers, not an emergency.

What the audit checks

For every page in the sitemap, the script parses each <a href> and records the URL, the rel tokens, the target, the anchor text, whether it sits inside <footer>, and whether any parent element has a class or id that looks like comments or reviews. Then it flags:

  • Finding: paid_unqualified; Severity: fix; Rule: The URL looks like an affiliate link (query keys such as tag, aff, affiliate, partner, or a /go/ or /recommends/ path) and has neither sponsored nor nofollow
  • Finding: sponsored_page_unqualified; Severity: fix; Rule: The page text says "sponsored post," "paid partnership," "advertisement" or "#ad," and a link in the content (not the footer) has neither sponsored nor nofollow
  • Finding: ugc_unqualified; Severity: fix; Rule: The link sits inside a comments, reviews, guestbook or forum container and has no ugc, nofollow or sponsored
  • Finding: rel_typo; Severity: fix; Rule: A rel token is not a known value, for example nofolow or no-follow. A typo means the qualifier is missing
  • Finding: internal_nofollow; Severity: fix; Rule: A link to the same host carries nofollow. Google's page points to robots.txt for that job
  • Finding: http_outbound; Severity: review; Rule: An outbound link uses http://. Check whether the other site has an https:// version
  • Finding: sitewide_footer_link; Severity: review; Rule: An unqualified external link sits in the footer of at least 80% of pages. Your own social profiles are fine. A credit link you place on every client site is the case to think about
  • Finding: blank_without_noopener; Severity: info; Rule: target="_blank" without noopener or noreferrer
  • Finding: noreferrer; Severity: info; Rule: The destination will not see your site as the referrer. Fine for a map link, but a local partner who wants to see referral traffic from you will not

The affiliate patterns, the comment container words, and the sponsored phrases are my own heuristics, not Google rules. Edit the constants at the top for your clients' sites. The script cannot know whether a plain link was paid for. It can only point at links that look paid, sit on pages that say they are paid, or sit in places where visitors write.

The script

#!/usr/bin/env python3
"""Audit outbound links across a sitemap (standard library only).

Flags affiliate, sponsored and user-comment links without a rel qualifier,
rel typos, nofollow on internal links, http:// outbound links, sitewide
footer links and target=_blank links without noopener.

Usage: python3 outbound_audit.py http://localhost:8497/sitemap.xml [--csv report.csv]
"""
import csv, re, sys, time, urllib.request, xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit, parse_qs

UA = "outbound-link-audit/1.0 (+your-email@example.com)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
VALID_REL = {"nofollow", "sponsored", "ugc", "noopener", "noreferrer", "external",
             "author", "help", "license", "me", "next", "prev", "tag", "bookmark", "opener"}
QUALIFIERS = {"nofollow", "sponsored", "ugc"}
AFFILIATE_PARAMS = {"tag", "aff", "aff_id", "affid", "affiliate", "affiliate_id", "partner", "ref_id", "irclickid"}
AFFILIATE_PATH = re.compile(r"/(go|recommends|aff|affiliate|refer)/", re.I)
UGC_CONTAINER = re.compile(r"comment|review|guestbook|forum|ugc|testimonial", re.I)
SPONSORED_TEXT = re.compile(r"sponsored post|paid partnership|advertisement|#ad\b", re.I)
VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"}
SEVERITY = {"paid_unqualified": "fix", "sponsored_page_unqualified": "fix", "ugc_unqualified": "fix",
            "rel_typo": "fix", "internal_nofollow": "fix", "http_outbound": "review",
            "sitewide_footer_link": "review", "blank_without_noopener": "info", "noreferrer": "info"}
SITEWIDE_SHARE = 0.8   # an external URL on at least 80% of pages counts as sitewide


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.read().decode(r.headers.get_content_charset() or "utf-8", "replace")


def sitemap_urls(url):
    root = ET.fromstring(fetch(url))
    if root.tag == NS + "sitemapindex":
        out = []
        for loc in root.iter(NS + "loc"):
            out += sitemap_urls(loc.text.strip())
        return out
    return [loc.text.strip() for loc in root.iter(NS + "loc")]


class LinkParser(HTMLParser):
    """Collects <a href> links with rel, target, anchor text and context."""
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.stack, self.links, self.text, self.current = [], [], [], None

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "a" and a.get("href"):
            self.current = {"href": a["href"], "rel": a.get("rel") or "", "target": a.get("target") or "",
                            "in_footer": any(t == "footer" for t, _ in self.stack),
                            "ugc_context": any(UGC_CONTAINER.search(c) for _, c in self.stack), "text": ""}
        if tag not in VOID:
            self.stack.append((tag, f'{a.get("class") or ""} {a.get("id") or ""}'))

    def handle_endtag(self, tag):
        if tag == "a" and self.current:
            self.links.append(self.current)
            self.current = None
        for i in range(len(self.stack) - 1, -1, -1):
            if self.stack[i][0] == tag:
                del self.stack[i:]
                break

    def handle_data(self, data):
        self.text.append(data)
        if self.current is not None:
            self.current["text"] += data


def rel_tokens(rel):
    return [t for t in re.split(r"[\s,]+", rel.lower()) if t]


def looks_affiliate(url):
    parts = urlsplit(url)
    keys = {k.lower() for k in parse_qs(parts.query)}
    return bool(keys & AFFILIATE_PARAMS) or bool(AFFILIATE_PATH.search(parts.path))


def audit(sitemap):
    site_host = urlsplit(sitemap).netloc.lower()
    pages = sitemap_urls(sitemap)
    rows, ext_pages = [], defaultdict(set)
    for page in pages:
        try:
            html = fetch(page)
        except Exception as e:
            print(f"  could not fetch {page}: {e}", file=sys.stderr)
            continue
        p = LinkParser()
        p.feed(html)
        sponsored_page = bool(SPONSORED_TEXT.search(" ".join(p.text)))
        for link in p.links:
            url = urljoin(page, link["href"])
            parts = urlsplit(url)
            if parts.scheme not in ("http", "https"):
                continue          # mailto:, tel:, javascript: are out of scope
            internal = parts.netloc.lower() == site_host
            rel = rel_tokens(link["rel"])
            qualified = bool(QUALIFIERS & set(rel))
            issues = [f"rel_typo:{t}" for t in rel if t not in VALID_REL]
            if internal:
                if "nofollow" in rel:
                    issues.append("internal_nofollow")
            else:
                ext_pages[url].add(page)
                if looks_affiliate(url) and not ({"sponsored", "nofollow"} & set(rel)):
                    issues.append("paid_unqualified")
                elif sponsored_page and not link["in_footer"] and not ({"sponsored", "nofollow"} & set(rel)):
                    issues.append("sponsored_page_unqualified")
                if link["ugc_context"] and not qualified:
                    issues.append("ugc_unqualified")
                if parts.scheme == "http":
                    issues.append("http_outbound")
                if link["target"].lower() == "_blank" and "noopener" not in rel and "noreferrer" not in rel:
                    issues.append("blank_without_noopener")
                if "noreferrer" in rel:
                    issues.append("noreferrer")
            rows.append({"page": page, "url": url, "internal": internal, "rel": " ".join(rel),
                         "target": link["target"], "text": " ".join(link["text"].split())[:60],
                         "in_footer": link["in_footer"], "issues": issues})
        time.sleep(0.2)   # be gentle
    # External links in the footer of most pages (credits, partner badges, social profiles)
    for r in rows:
        share = len(ext_pages.get(r["url"], ())) / max(len(pages), 1)
        if not r["internal"] and r["in_footer"] and share >= SITEWIDE_SHARE \
                and not (QUALIFIERS & set(r["rel"].split())):
            r["issues"].append("sitewide_footer_link")
    return pages, rows, ext_pages


def kind(issue):
    return issue.split(":")[0]


def main():
    args = sys.argv[1:]
    if not args:
        sys.exit(__doc__)
    csv_path = args[args.index("--csv") + 1] if "--csv" in args else None
    pages, rows, ext_pages = audit(args[0])
    ext = [r for r in rows if not r["internal"]]
    print(f"Pages in sitemap: {len(pages)}")
    print(f"Links found: {len(rows)} ({len(ext)} outbound to {len({urlsplit(r['url']).netloc for r in ext})} domains)")
    # One finding per link per page; a footer link repeated on every page counts once
    findings = {}
    for r in rows:
        if not r["issues"]:
            continue
        sitewide = r["in_footer"] and len(ext_pages.get(r["url"], ())) > 1
        key = ("footer", r["url"]) if sitewide else (r["page"], r["url"])
        f = findings.setdefault(key, dict(r, issues=[], where="footer, every page" if sitewide
                                          else urlsplit(r["page"]).path))
        f["issues"] += [i for i in r["issues"] if i not in f["issues"]]
    counts = Counter(kind(i) for f in findings.values() for i in f["issues"])
    print("\nFindings by type (footer links counted once):")
    for name in SEVERITY:
        if counts[name]:
            print(f"  [{SEVERITY[name]:6}] {name:28} {counts[name]}")
    print("\nLinks to check:")
    for f in findings.values():
        print(f"  {f['where']}\n    -> {f['url']}  rel=\"{f['rel']}\"  ({f['text']})\n       {', '.join(f['issues'])}")
    print("\nOutbound domains:")
    by_domain = defaultdict(Counter)
    for r in ext:
        rel = set(r["rel"].split())
        by_domain[urlsplit(r["url"]).netloc]["qualified" if QUALIFIERS & rel else "plain"] += 1
    for d, c in sorted(by_domain.items(), key=lambda x: -sum(x[1].values())):
        print(f"  {d:34} links={sum(c.values()):3}  plain={c['plain']:3}  qualified={c['qualified']:3}")
    if csv_path:
        with open(csv_path, "w", newline="") as f:
            w = csv.writer(f)
            w.writerow(["page", "url", "internal", "rel", "target", "anchor_text", "in_footer", "issues"])
            for r in rows:
                w.writerow([r["page"], r["url"], r["internal"], r["rel"], r["target"], r["text"],
                            r["in_footer"], ";".join(r["issues"])])
        print(f"\nCSV written: {csv_path}")
    fix = any(SEVERITY[kind(i)] == "fix" for r in rows for i in r["issues"])
    sys.exit(1 if fix else 0)


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

A few choices worth explaining:

  • html.parser keeps a stack of open elements, so each link knows whether it sits inside a <footer> or a container whose class or id contains "comment," "review" and similar words. Void elements such as <img> and <br> are not pushed onto the stack.
  • rel is split on spaces and commas, because Google accepts both.
  • mailto:, tel: and javascript: links are skipped. They are not outbound web links.
  • Footer links are counted once. A footer credit on eight pages is one decision, not eight problems.
  • Exit code 1 when any "fix" finding exists, 0 otherwise, so you can run it on a schedule or in CI.

The test site

The fixture is "Copperline Bakery" (fictional), served by a small standard library server on localhost:8497. It has 8 pages in its sitemap. In "before" mode I planted problems on six of the pages and in the footer:

  • Page: /; What is on it: A delivery partner link with target="_blank" and no rel
  • Page: /about; What is on it: A supplier link (fine) and an http:// chamber of commerce link
  • Page: /blog/best-stand-mixers-for-home-bakers; What is on it: Two affiliate links with ?tag=, one with no rel and one with rel="nofolow"; one /go/ link correctly marked rel="nofollow, sponsored"; one editorial link
  • Page: /blog/holiday-market-sponsored; What is on it: A post that says "paid partnership," with one unqualified ticket link and one correctly marked map link
  • Page: /reviews; What is on it: Three customer comments with links: one plain, one spam, one with rel="ugc"
  • Page: /contact; What is on it: A map link with noopener noreferrer, and an internal link to /privacy marked nofollow
  • Page: /menu, /privacy; What is on it: No outbound links
  • Page: Footer, every page; What is on it: An Instagram link with noopener, and "Website by Brightside Web" as a plain http:// link
"""Fixture server for 'Copperline Bakery' (fictional local bakery). Usage: serve_fixture.py [before|after]
HTTP on localhost:8497. All external domains are .example hosts and are never fetched.

before: affiliate, sponsored and comment links have no rel qualifier, one rel typo, an internal nofollow,
        an http:// agency credit link in the footer of every page, and target=_blank links without noopener.
after:  the same pages with those links qualified or fixed.
"""
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from xml.sax.saxutils import escape

MODE = sys.argv[1] if len(sys.argv) > 1 else "before"
PORT = 8497
BASE = f"http://localhost:{PORT}"
A = MODE == "after"

def footer():
    credit = ('<a href="https://brightside-web.example/" rel="nofollow">Website by Brightside Web</a>' if A
              else '<a href="http://brightside-web.example/">Website by Brightside Web</a>')
    return f"""<footer><p>Copperline Bakery, 14 Mill Lane, Easton</p>
<a href="https://social.example.com/copperlinebakery" target="_blank" rel="noopener">Instagram</a>
{credit}</footer>"""

def page(title, body):
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{title} | Copperline Bakery</title></head>
<body><header><nav><a href="/">Home</a> <a href="/menu">Menu</a> <a href="/about">About</a>
<a href="/blog/best-stand-mixers-for-home-bakers">Blog</a> <a href="/reviews">Reviews</a> <a href="/contact">Contact</a></nav></header>
<main>{body}</main>{footer()}</body></html>"""

order_rel = ' rel="noopener"' if A else ''
PAGES = {
 "/": page("Home", f"""<h1>Fresh bread in Easton since 2009</h1>
<p>Order ahead for pickup or delivery through our
<a href="https://order.delivery.example/copperline" target="_blank"{order_rel}>delivery partner</a>.</p>
<p>See today's <a href="/menu">menu</a>.</p>"""),
 "/menu": page("Menu", "<h1>Menu</h1><p>Sourdough, rye, seeded loaf, cinnamon buns.</p>"),
 "/about": page("About", f"""<h1>About us</h1>
<p>Our flour comes from <a href="https://millbrookfarm.example.com/">Millbrook Farm</a>, twenty minutes north.</p>
<p>We are members of the <a href="{'https' if A else 'http'}://chamber.easton.example.org/members">Easton Chamber of Commerce</a>.</p>"""),
 "/blog/best-stand-mixers-for-home-bakers": page("Best stand mixers for home bakers", f"""<h1>The stand mixers we would buy for a home kitchen</h1>
<p>We earn a commission if you buy through some links on this page.</p>
<p>Our pick: the <a href="https://shop.example.com/mixer-500?tag=copperline-20"{' rel="sponsored"' if A else ''}>Model 500 mixer</a>.</p>
<p>Budget pick: the <a href="https://shop.example.com/mixer-300?tag=copperline-20" rel="{'sponsored' if A else 'nofolow'}">Model 300</a>.</p>
<p>For big batches: <a href="https://kitchenstore.example.com/go/copperline" rel="nofollow, sponsored">the Model 700</a>.</p>
<p>How we test: <a href="https://testing-standards.example.org/mixers">an independent guide we trust</a>.</p>"""),
 "/blog/holiday-market-sponsored": page("Holiday market", f"""<h1>Find us at the Riverside Holiday Market</h1>
<p><strong>Sponsored post:</strong> this is a paid partnership with Riverside Holiday Market.</p>
<p>Buy tickets on the <a href="https://riversidemarket.example.com/tickets"{' rel="sponsored"' if A else ''}>market website</a>.</p>
<p>Vendor map: <a href="https://riversidemarket.example.com/map" rel="sponsored noopener" target="_blank">open map</a>.</p>"""),
 "/reviews": page("Reviews", f"""<h1>What customers say</h1>
<section class="customer-comments">
<div class="comment"><p>Best rye in town. My blog post about it: <a href="https://janesfoodblog.example.net/rye"{' rel="ugc"' if A else ''}>Jane's Food Blog</a></p></div>
<div class="comment"><p>Cheap flights to anywhere! <a href="https://cheap-flights.example.biz/?ref=spam"{' rel="ugc nofollow"' if A else ''}>click here</a></p></div>
<div class="comment"><p>Lovely staff. <a href="https://tomsphotos.example.org/" rel="ugc">Tom's photos</a></p></div>
</section>"""),
 "/contact": page("Contact", f"""<h1>Contact</h1>
<p>Call 555-0142 or find us on <a href="https://maps.example.com/?q=14+Mill+Lane+Easton" target="_blank" rel="noopener noreferrer">the map</a>.</p>
<p>Read our <a href="/privacy"{'' if A else ' rel="nofollow"'}>privacy notice</a>.</p>"""),
 "/privacy": page("Privacy", "<h1>Privacy notice</h1><p>We keep order details for 12 months.</p>"),
}

class H(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def _send(self, code, body, ctype="text/html; charset=utf-8"):
        b = body.encode()
        self.send_response(code); self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(b))); self.end_headers()
        if self.command != "HEAD": self.wfile.write(b)
    def do_HEAD(self): self.do_GET()
    def do_GET(self):
        p = self.path.split("?")[0]
        if p == "/sitemap.xml":
            locs = "".join(f"<url><loc>{escape(BASE + u)}</loc></url>" for u in PAGES)
            return self._send(200, f'<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{locs}</urlset>', "application/xml")
        if p in PAGES: return self._send(200, PAGES[p])
        self._send(404, page("Not found", "<h1>Not found</h1>"))

if __name__ == "__main__":
    print(f"Serving Copperline Bakery fixture ({MODE}) on {BASE}", flush=True)
    ThreadingHTTPServer(("localhost", PORT), H).serve_forever()
Enter fullscreen mode Exit fullscreen mode

Running it: before

$ python3 serve_fixture.py before &
$ python3 outbound_audit.py http://localhost:8497/sitemap.xml --csv outbound_report_before.csv
Pages in sitemap: 8
Links found: 79 (29 outbound to 13 domains)

Findings by type (footer links counted once):
  [fix   ] paid_unqualified             2
  [fix   ] sponsored_page_unqualified   1
  [fix   ] ugc_unqualified              2
  [fix   ] rel_typo                     1
  [fix   ] internal_nofollow            1
  [review] http_outbound                2
  [review] sitewide_footer_link         2
  [info  ] blank_without_noopener       1
  [info  ] noreferrer                   1

Links to check:
  /
    -> https://order.delivery.example/copperline  rel=""  (delivery partner)
       blank_without_noopener
  footer, every page
    -> https://social.example.com/copperlinebakery  rel="noopener"  (Instagram)
       sitewide_footer_link
  footer, every page
    -> http://brightside-web.example/  rel=""  (Website by Brightside Web)
       http_outbound, sitewide_footer_link
  /about
    -> http://chamber.easton.example.org/members  rel=""  (Easton Chamber of Commerce)
       http_outbound
  /blog/best-stand-mixers-for-home-bakers
    -> https://shop.example.com/mixer-500?tag=copperline-20  rel=""  (Model 500 mixer)
       paid_unqualified
  /blog/best-stand-mixers-for-home-bakers
    -> https://shop.example.com/mixer-300?tag=copperline-20  rel="nofolow"  (Model 300)
       rel_typo:nofolow, paid_unqualified
  /blog/holiday-market-sponsored
    -> https://riversidemarket.example.com/tickets  rel=""  (market website)
       sponsored_page_unqualified
  /reviews
    -> https://janesfoodblog.example.net/rye  rel=""  (Jane's Food Blog)
       ugc_unqualified
  /reviews
    -> https://cheap-flights.example.biz/?ref=spam  rel=""  (click here)
       ugc_unqualified
  /contact
    -> https://maps.example.com/?q=14+Mill+Lane+Easton  rel="noopener noreferrer"  (the map)
       noreferrer
  /contact
    -> http://localhost:8497/privacy  rel="nofollow"  (privacy notice)
       internal_nofollow

Outbound domains:
  social.example.com                 links=  8  plain=  8  qualified=  0
  brightside-web.example             links=  8  plain=  8  qualified=  0
  shop.example.com                   links=  2  plain=  2  qualified=  0
  riversidemarket.example.com        links=  2  plain=  1  qualified=  1
  order.delivery.example             links=  1  plain=  1  qualified=  0
  millbrookfarm.example.com          links=  1  plain=  1  qualified=  0
  chamber.easton.example.org         links=  1  plain=  1  qualified=  0
  kitchenstore.example.com           links=  1  plain=  0  qualified=  1
  testing-standards.example.org      links=  1  plain=  1  qualified=  0
  janesfoodblog.example.net          links=  1  plain=  1  qualified=  0
  cheap-flights.example.biz          links=  1  plain=  1  qualified=  0
  tomsphotos.example.org             links=  1  plain=  0  qualified=  1
  maps.example.com                   links=  1  plain=  1  qualified=  0

CSV written: outbound_report_before.csv
$ echo $?
1
Enter fullscreen mode Exit fullscreen mode

What it found, in plain words:

  • Two affiliate links pass as editorial links. The Model 300 link was meant to be qualified, but nofolow is not a value anything recognizes, so it is reported twice: as a typo and as an unqualified paid link. The /go/ link with rel="nofollow, sponsored" passed, which confirms the comma handling works.
  • The sponsored post's main link has no qualifier, while the map link on the same page does. This mix is common when one person writes the post and another adds links later.
  • Two comment links have no ugc, including the spam one. Tom's link, already marked ugc, passed.
  • The privacy link is nofollow. It is an internal link, so this does nothing useful for crawling control.
  • The footer credit is http:// and unqualified on every page. The Instagram link is listed for review too, and for a client's own profile the answer is "keep it."
  • The delivery link opens a new tab without noopener. MDN says modern browsers apply noopener behavior anyway, so this is a note, not a fix.

Fixing it

  1. Affiliate links: add rel="sponsored". If the client's CMS has an affiliate link plugin, set the default there so new links get it.
  2. Sponsored posts: add rel="sponsored" to every link in the paid content that points at the sponsor, and keep the written disclosure on the page.
  3. Comments and reviews: set the comment system to add rel="ugc" (or ugc nofollow) to all user links. Delete the spam comment rather than qualifying it.
  4. Typos: fix the rel value. Then search the theme and templates for the same typo, since it usually came from one copied snippet.
  5. Internal nofollow: remove it. If a page should stay out of search results, use noindex on the page. If it should not be crawled, use robots.txt.
  6. http:// links: switch to https:// where the other site supports it.
  7. Footer credit: decide as an agency. In the "after" version I kept the credit, switched it to https:// and added rel="nofollow".

Running it: after

$ python3 serve_fixture.py after &
$ python3 outbound_audit.py http://localhost:8497/sitemap.xml --csv outbound_report_after.csv
Pages in sitemap: 8
Links found: 79 (29 outbound to 13 domains)

Findings by type (footer links counted once):
  [review] sitewide_footer_link         1
  [info  ] noreferrer                   1

Links to check:
  footer, every page
    -> https://social.example.com/copperlinebakery  rel="noopener"  (Instagram)
       sitewide_footer_link
  /contact
    -> https://maps.example.com/?q=14+Mill+Lane+Easton  rel="noopener noreferrer"  (the map)
       noreferrer

Outbound domains:
  social.example.com                 links=  8  plain=  8  qualified=  0
  brightside-web.example             links=  8  plain=  0  qualified=  8
  shop.example.com                   links=  2  plain=  0  qualified=  2
  riversidemarket.example.com        links=  2  plain=  0  qualified=  2
  order.delivery.example             links=  1  plain=  1  qualified=  0
  millbrookfarm.example.com          links=  1  plain=  1  qualified=  0
  chamber.easton.example.org         links=  1  plain=  1  qualified=  0
  kitchenstore.example.com           links=  1  plain=  0  qualified=  1
  testing-standards.example.org      links=  1  plain=  1  qualified=  0
  janesfoodblog.example.net          links=  1  plain=  0  qualified=  1
  cheap-flights.example.biz          links=  1  plain=  0  qualified=  1
  tomsphotos.example.org             links=  1  plain=  0  qualified=  1
  maps.example.com                   links=  1  plain=  1  qualified=  0

CSV written: outbound_report_after.csv
$ echo $?
0
Enter fullscreen mode Exit fullscreen mode

The exit code is now 0. Two items remain on purpose: the Instagram profile link (a review item, and correct as it is) and the map link with noreferrer (info only). The domain table at the bottom is the part I paste into client reports: one line per outside domain, with how many links are plain and how many are qualified. A domain that suddenly shows up with dozens of plain links is worth a look.

Running it on a client site

python3 outbound_audit.py https://client-site.example/sitemap.xml --csv client-outbound.csv
Enter fullscreen mode Exit fullscreen mode

Some tips:

  • The script makes one request per sitemap URL and waits 0.2 seconds between pages. That is gentle enough for a small business site. Raise the delay for larger sites.
  • It follows sitemap index files. It does not crawl pages that are missing from the sitemap, so links on those pages are not checked.
  • Set a real contact address in the UA string. Some hosts block the default Python user agent.
  • Run it only on sites you own or have permission to test.
  • If a client uses a different word for its comments container (say, class="feedback"), add it to UGC_CONTAINER.
  • The script does not check whether outbound links still work. That is a separate job with different rules for timeouts and retries.

Related free tools

Two free Appie tools help with the scoping step. The Sitemap URL Extractor takes a sitemap URL or pasted XML and returns one URL per line; for a sitemap index it lists the child sitemap locations, which you then open one at a time. The Website URL Extractor collects same-host links from up to 80 HTML pages (or until 12 seconds pass), which helps you spot pages that are linked on the site but missing from the sitemap. Both ask you to complete a captcha before they run.

FAQ

Do I need rel on every outbound link?
No. Google's page says regular links need no rel attribute. Qualify the paid, sponsored and user-generated ones.

Is nofollow still OK for affiliate links?
Google's page says it is "still an acceptable way to flag them, though sponsored is preferred." You can also use both: rel="sponsored nofollow".

Should I add noopener to every target="_blank" link?
It does no harm and covers older browsers, but MDN says target="_blank" already implies noopener behavior. I treat it as a cleanup item, not a priority.

Is an agency credit link in the footer against Google's rules?
Google's link spam examples include "widely distributed links in the footers or templates of various sites." A credit link on many client sites fits that description, so many agencies qualify it with nofollow or move it to an About or Credits page. That decision is yours and the client's.

Can this replace a crawler?
No. It checks what the sitemap lists. A crawler also finds pages that are not in the sitemap. For a small client site, the sitemap is usually close enough for a monthly check.


RG, Founder, Appie.run

Top comments (0)