DEV Community

appierun
appierun

Posted on

Inventory Third-Party Scripts and Tracking Tags Across Your Sitemap with Python (Standard Library Only)

When an agency takes over a local client's website, the analytics are usually the first thing that turns out to be wrong. The numbers in the report look odd, and the reason is almost always in the HTML: a GA4 tag pasted twice, a Universal Analytics tag that has not sent data in years, a second GA4 property that a previous freelancer set up on one page, or a chat widget and a heatmap tool that nobody remembers adding.

None of this is visible by looking at the site. You have to read the source of every page, and on a 40-page site nobody does that by hand.

This tutorial builds a small Python script, standard library only, that reads a sitemap, fetches every page and reports:

  • every third-party host the pages load scripts, iframes, stylesheets or images from, with how many pages use each one,
  • every tracking ID it can recognise (GA4 G-, Universal Analytics UA-, Tag Manager GTM-, Google Ads AW-, and Meta Pixel IDs from fbq('init', ...)), with page counts,
  • the same tag loaded twice on one page, which usually means double-counted page views,
  • Universal Analytics tags still in the HTML,
  • more than one GA4 ID across the site, and tags that run on some pages but not others,
  • third-party scripts or iframes loaded over plain http://,
  • script hosts that appear on a single page, which are often leftovers.

I ran it for real against a small fictional site on localhost, so every line of output below is real output from the script. The site, "Harbor Lane Dental", is made up for this tutorial, every tag ID is invented, and the vendor hosts use the reserved .example domain. The script only parses HTML, so it never contacts any of the third-party hosts.

Disclosure: I work on Appie.run. Two free sitemap tools on appie.run are mentioned near the end; the script does not need them.

Why this matters for a local business site

Three reasons, in the order clients usually feel them:

  1. Wrong numbers. A GA4 tag that loads twice on the home page inflates page views on that page. A second GA4 ID on the contact page sends those visits to a property nobody looks at, so the "contact page views" in the report drop to zero. A blog post with no tag at all is invisible.
  2. Dead tags. Google says standard Universal Analytics properties stopped processing data on 1 July 2023, and that access to UA data and the interface ended from the week of 1 July 2024 (Google Analytics Help, "Google Analytics 4 has replaced Universal Analytics", read 4 Dec 2026). A UA- tag still on a page does nothing useful, but it still loads a script.
  3. Forgotten vendors. Every third-party script is code from another company running on your client's site. A heatmap tool from a trial two years ago, or a chat loader still pulled over http://, is worth knowing about. On an HTTPS page, browsers block an http:// script as mixed content, so that widget may already be broken. We covered mixed content in more depth in an earlier post on finding mixed content across a sitemap.

This script is an inventory, not a privacy or consent review. It tells you what the HTML loads. Whether each tag should be there, and under what consent setup, is a decision for the client and whoever advises them.

What the script can and cannot see

It reads the HTML the server sends. That has two limits worth knowing before you trust the output:

  • Tag Manager hides tags. If a site loads Google Tag Manager, the tags inside the container (GA4, ads pixels, anything else) are added by JavaScript after the page loads. The script will report the GTM- container ID, but not what is inside it. Open the container itself to see those.
  • JavaScript-added scripts are invisible. Anything a script injects at runtime, such as a chat widget that loads three more files, will not show up. You only see the first file.

For a typical small business site built on a theme or page builder, most tags are pasted straight into the HTML, so the inventory still catches most of what matters.

The fixture site

The fictional site has five pages: home, services, booking, one blog post and contact. The "before" version has the problems I see most often on inherited client sites:

  • the home page loads the GA4 tag twice (once in the theme settings, once in an old header snippet),
  • the booking page still has a Universal Analytics tag and no GA4 tag,
  • the contact page uses a different GA4 ID from the rest of the site,
  • the blog post has no analytics tag at all,
  • the chat widget loads over http:// on every page,
  • a heatmap script sits on the services page only,
  • the ads pixel only runs on the home and booking pages.

The "after" version fixes all of that, except that the blog post deliberately carries no ads pixel, which gives us one warning to discuss.

The fixture is a tiny http.server app on port 8504 that serves a sitemap and five pages. It takes before or after as its argument.

The script

Save this as tag_inventory.py. It needs Python 3.9 or later and nothing outside the standard library.

#!/usr/bin/env python3
"""Inventory third-party hosts and tracking tags across every page in a sitemap.
Standard library only. Usage: python3 tag_inventory.py SITEMAP_URL [--csv report.csv]
Exit code 1 if any ERROR is found."""
import csv
import re
import sys
import urllib.request
import xml.etree.ElementTree as ET
from collections import defaultdict
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit

UA = "tag-inventory/1.0 (+standard library audit script)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"

# Tag ID patterns, checked against script URLs and inline script text.
TAG_PATTERNS = [
    ("GA4", re.compile(r"\bG-[A-Z0-9]{6,12}\b")),
    ("Universal Analytics", re.compile(r"\bUA-\d{4,10}-\d{1,4}\b")),
    ("Tag Manager", re.compile(r"\bGTM-[A-Z0-9]{4,9}\b")),
    ("Google Ads", re.compile(r"\bAW-\d{6,12}\b")),
    ("Meta Pixel", re.compile(r"fbq\(\s*['\"]init['\"]\s*,\s*['\"](\d{10,20})['\"]")),
]


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=15) 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 PageParser(HTMLParser):
    """Collects external resource URLs (with element type) and inline script text."""
    def __init__(self, base):
        super().__init__(convert_charrefs=True)
        self.base, self.resources, self.inline, self._in_script = base, [], [], False

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "script":
            if a.get("src"):
                self.resources.append(("script", urljoin(self.base, a["src"])))
            else:
                self._in_script = True
        elif tag == "iframe" and a.get("src"):
            self.resources.append(("iframe", urljoin(self.base, a["src"])))
        elif tag == "link" and a.get("href") and "stylesheet" in (a.get("rel") or "").lower():
            self.resources.append(("stylesheet", urljoin(self.base, a["href"])))
        elif tag == "img" and a.get("src"):
            self.resources.append(("img", urljoin(self.base, a["src"])))

    def handle_endtag(self, tag):
        if tag == "script":
            self._in_script = False

    def handle_data(self, data):
        if self._in_script:
            self.inline.append(data)


def find_tags(text):
    """Return a list of (kind, id) for every tag ID in text, keeping repeats."""
    found = []
    for kind, pat in TAG_PATTERNS:
        for m in pat.finditer(text):
            found.append((kind, m.group(1) if pat.groups else m.group(0)))
    return found


def audit(sitemap):
    urls = sitemap_urls(sitemap)
    site_host = urlsplit(urls[0]).hostname if urls else ""
    hosts = defaultdict(lambda: {"types": set(), "pages": set()})
    tag_pages = defaultdict(set)          # (kind, id) -> pages
    findings = []                         # (severity, page, message)
    insecure = defaultdict(set)           # (type, url) -> pages loading it over http

    for url in urls:
        try:
            html = fetch(url)
        except Exception as e:  # noqa: BLE001
            findings.append(("ERROR", url, f"could not fetch page: {e}"))
            continue
        p = PageParser(url)
        p.feed(html)

        for kind, res in p.resources:
            parts = urlsplit(res)
            if parts.hostname and parts.hostname != site_host:
                hosts[parts.hostname]["types"].add(kind)
                hosts[parts.hostname]["pages"].add(url)
                if parts.scheme == "http" and kind in ("script", "iframe"):
                    insecure[(kind, res)].add(url)

        # Tag IDs from script URLs and inline scripts. A gtag.js URL and its config call
        # name the same ID, so count loads by the script URL when there is one.
        src_tags = []
        for kind, res in p.resources:
            if kind == "script":
                src_tags += find_tags(res)
        inline_tags = find_tags(" ".join(p.inline))
        page_tags = set(src_tags) | set(inline_tags)
        for t in page_tags:
            tag_pages[t].add(url)

        for t in set(src_tags):
            n = src_tags.count(t)
            if n > 1:
                findings.append(("ERROR", url, f"{t[0]} {t[1]} loaded {n} times on one page (double counting)"))
        for kind, tid in page_tags:
            if kind == "Universal Analytics":
                findings.append(("ERROR", url, f"Universal Analytics tag {tid} still on page (UA stopped processing data in 2023)"))
        if not any(k in ("GA4", "Tag Manager") for k, _ in page_tags):
            findings.append(("WARN", url, "no GA4 or Tag Manager tag found on this page"))

    total = len(urls)
    for (kind, res), pages in sorted(insecure.items()):
        findings.append(("ERROR", "(site)", f"third-party {kind} over plain http on {len(pages)}/{total} pages: {res}"))
    ga4_ids = sorted(tid for kind, tid in tag_pages if kind == "GA4")
    if len(ga4_ids) > 1:
        findings.append(("WARN", "(site)", f"{len(ga4_ids)} different GA4 IDs in use: {', '.join(ga4_ids)}"))
    for (kind, tid), pages in sorted(tag_pages.items()):
        if kind != "Universal Analytics" and 1 < len(pages) < total:
            missing = sorted(set(urls) - pages)
            findings.append(("WARN", "(site)", f"{kind} {tid} on {len(pages)}/{total} pages; missing on: "
                             + ", ".join(urlsplit(m).path for m in missing)))
    for host, info in sorted(hosts.items()):
        if len(info["pages"]) == 1 and total > 2 and "script" in info["types"]:
            page = urlsplit(next(iter(info["pages"]))).path
            findings.append(("INFO", "(site)", f"script host {host} appears on 1 page only ({page}); leftover or intended?"))
    return urls, hosts, tag_pages, findings


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
    urls, hosts, tag_pages, findings = audit(args[0])
    total = len(urls)

    print(f"Pages in sitemap: {total}\n")
    print("Third-party hosts")
    for host, info in sorted(hosts.items(), key=lambda kv: (-len(kv[1]["pages"]), kv[0])):
        print(f"  {host:32} {len(info['pages'])}/{total} pages  {', '.join(sorted(info['types']))}")
    print("\nTracking tags")
    for (kind, tid), pages in sorted(tag_pages.items(), key=lambda kv: (kv[0][0], kv[0][1])):
        print(f"  {kind:20} {tid:18} {len(pages)}/{total} pages")
    print("\nFindings")
    order = {"ERROR": 0, "WARN": 1, "INFO": 2}
    for sev, page, msg in sorted(findings, key=lambda f: (order[f[0]], f[1])):
        where = urlsplit(page).path if page.startswith("http") else page
        print(f"  {sev:5} {where}  {msg}")
    counts = {s: sum(1 for f in findings if f[0] == s) for s in order}
    print(f"\nSummary: {counts['ERROR']} errors, {counts['WARN']} warnings, {counts['INFO']} info")

    if csv_path:
        with open(csv_path, "w", newline="") as fh:
            w = csv.writer(fh)
            w.writerow(["severity", "page", "message"])
            w.writerows(findings)
    sys.exit(1 if counts["ERROR"] else 0)


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

A few design choices worth explaining:

  • Counting loads by script URL. A standard GA4 snippet names the ID twice: once in the gtag/js?id= URL and once in gtag('config', ...). If the script counted every mention, every page would look like a double load. So it counts loads from <script src> URLs and uses inline text only to know which IDs are present. That is how it catches the real duplicate on the home page without flagging every normal page.
  • "On some pages but not all" is a warning, not an error. Some tags should only run on some pages. The script cannot know your intent, so it lists the missing pages and leaves the call to you.
  • Single-page script hosts are info only. A booking widget on the booking page is supposed to be there. A heatmap script on one page probably is not. The script raises both and lets you decide.
  • The http check is grouped by resource. One chat loader on every page is one problem, so it is reported once with a page count.

Run 1: the "before" site

python3 serve_fixture.py before &
python3 tag_inventory.py http://localhost:8504/sitemap.xml --csv report_before.csv
Enter fullscreen mode Exit fullscreen mode

Output:

Pages in sitemap: 5

Third-party hosts
  fonts.typecdn.example            5/5 pages  stylesheet
  widgets.chatdesk.example         5/5 pages  script
  www.googletagmanager.com         3/5 pages  script
  book.slotly.example              1/5 pages  iframe, script
  cdn.heatmapr.example             1/5 pages  script
  maps.mapframe.example            1/5 pages  iframe
  www.google-analytics.com         1/5 pages  script

Tracking tags
  GA4                  G-7TQ2W81LZD       1/5 pages
  GA4                  G-HLD4K2M9QX       2/5 pages
  Meta Pixel           301958274610       2/5 pages
  Universal Analytics  UA-48210937-1      1/5 pages

Findings
  ERROR (site)  third-party script over plain http on 5/5 pages: http://widgets.chatdesk.example/loader.js
  ERROR /  GA4 G-HLD4K2M9QX loaded 2 times on one page (double counting)
  ERROR /book/  Universal Analytics tag UA-48210937-1 still on page (UA stopped processing data in 2023)
  WARN  (site)  2 different GA4 IDs in use: G-7TQ2W81LZD, G-HLD4K2M9QX
  WARN  (site)  GA4 G-HLD4K2M9QX on 2/5 pages; missing on: /blog/winter-tooth-sensitivity/, /book/, /contact/
  WARN  (site)  Meta Pixel 301958274610 on 2/5 pages; missing on: /blog/winter-tooth-sensitivity/, /contact/, /services/
  WARN  /blog/winter-tooth-sensitivity/  no GA4 or Tag Manager tag found on this page
  WARN  /book/  no GA4 or Tag Manager tag found on this page
  INFO  (site)  script host book.slotly.example appears on 1 page only (/book/); leftover or intended?
  INFO  (site)  script host cdn.heatmapr.example appears on 1 page only (/services/); leftover or intended?
  INFO  (site)  script host www.google-analytics.com appears on 1 page only (/book/); leftover or intended?

Summary: 3 errors, 5 warnings, 3 info

Enter fullscreen mode Exit fullscreen mode

Reading it top to bottom:

  • Third-party hosts is the list to send to the client with one question: "Do you know what each of these is, and do you still use it?" Seven hosts on a five-page dental site is not unusual.
  • Tracking tags already tells the story. Two GA4 IDs, the main one on only two of five pages, a UA tag and a pixel on two pages.
  • Errors: the http:// chat loader on every page, the double GA4 load on the home page, and the UA tag on the booking page.
  • Warnings: the second GA4 ID, the gaps in GA4 and pixel coverage, and two pages with no GA4 or Tag Manager tag at all. The booking page warning is the one that matters most commercially: the page where people book is the page analytics cannot see.
  • Info: three hosts on a single page. The booking widget is intended; the heatmap and the old google-analytics.com loader are leftovers.

The exit code is 1, so this would fail a CI job or a scheduled check.

The fixes

On the fictional site, the fixes were:

  1. Remove the GA4 snippet from the old header block and keep the one in the theme settings.
  2. Remove the Universal Analytics code from the booking page and add the site's GA4 tag.
  3. Replace the stray GA4 ID on the contact page with the main one. Before you do this on a real site, check with the client who owns the second property and whether anything reports from it.
  4. Add the GA4 tag to the blog template.
  5. Change the chat loader URL to https:// (check the vendor's current embed code rather than just editing the scheme).
  6. Remove the heatmap script after confirming the trial has ended.
  7. Add the ads pixel to the services and contact pages, the pages the client wants to measure.

Run 2: the "after" site

python3 serve_fixture.py after &
python3 tag_inventory.py http://localhost:8504/sitemap.xml --csv report_after.csv
Enter fullscreen mode Exit fullscreen mode

Output:

Pages in sitemap: 5

Third-party hosts
  fonts.typecdn.example            5/5 pages  stylesheet
  widgets.chatdesk.example         5/5 pages  script
  www.googletagmanager.com         5/5 pages  script
  book.slotly.example              1/5 pages  iframe, script
  maps.mapframe.example            1/5 pages  iframe

Tracking tags
  GA4                  G-HLD4K2M9QX       5/5 pages
  Meta Pixel           301958274610       4/5 pages

Findings
  WARN  (site)  Meta Pixel 301958274610 on 4/5 pages; missing on: /blog/winter-tooth-sensitivity/
  INFO  (site)  script host book.slotly.example appears on 1 page only (/book/); leftover or intended?

Summary: 0 errors, 1 warnings, 1 info

Enter fullscreen mode Exit fullscreen mode

The exit code is 0. One GA4 ID on all five pages, no UA tag, every script over HTTPS. The pixel warning remains because the blog post deliberately does not carry it, and the booking widget info line is expected. Keeping those two lines in the report is fine: anyone reading it next month can see they were looked at and accepted. If you want them gone, add an allowlist to the script.

What the script does not catch

  • Tags added by Tag Manager or by other scripts at runtime (see above). For those, open the container or use the browser's network panel.
  • Tag IDs in formats it does not know. The patterns list at the top is easy to extend with other vendors your clients use.
  • Whether a tag fires correctly. A tag can be present in the HTML and still send nothing because of an error, a consent setting or a blocked request. Check the GA4 realtime view or the vendor's own debugger.
  • Consent setup. The script does not check whether tags wait for consent. That needs a browser and a person who knows the client's requirements.
  • Pages missing from the sitemap. If a landing page is not in the sitemap, it is not audited.

Running it on a client site

  1. Find the sitemap. If you do not know where it is, the free Sitemap Finder and Checker on appie.run reads robots.txt and the usual sitemap paths and reports which sitemap files load and how many URLs they list. If you only want the list of page URLs, the Sitemap URL Extractor gives you one URL per line from a sitemap or a pasted sitemap XML (for a sitemap index it lists the child sitemaps, so run it again on a child file). Both ask you to complete a captcha before they run. I read both tool pages on 4 Dec 2026.
  2. Run the script against the sitemap URL. It sends one request per page, in sequence, so it is gentle on small sites.
  3. Send the "Third-party hosts" list to the client and ask what each one is.
  4. Fix the errors first, then decide on each warning.
  5. Run it again after any theme change, plugin install or new landing page. The usual way tags break is that someone pastes a snippet "just to test" and never removes it.

If you also check outbound links on the same sites, our outbound links and rel attributes post uses the same sitemap-first structure.

FAQ

Is it a problem to have both GA4 and Tag Manager on a page?
Not by itself. It becomes a problem when Tag Manager also fires a GA4 tag for the same ID, because then the page sends each hit twice. The script will show the GTM- container and the G- ID; open the container to see whether it fires GA4 too.

The script says a tag is missing on a page, but I can see it in the browser. Why?
It was probably added at runtime by Tag Manager or another script. The script reads the HTML the server sends, not the page after JavaScript has run.

Why flag Universal Analytics as an error if it does no harm?
It sends nothing useful, it still loads a script on every visit, and it tells you the page template has not been reviewed in a while. Removing it is a quick, safe fix.

Can I use it on a site with a sitemap index?
Yes. The sitemap_urls function follows a sitemap index and reads each child sitemap.

Can I run it in CI or on a schedule?
Yes. It exits with code 1 when it finds an error, and --csv writes every finding to a file you can keep with the client's records.

Files

All fixture files are in one folder: serve_fixture.py (the fictional site, before and after), tag_inventory.py (the script above), run-before.txt and run-after.txt (the outputs shown above), and report_before.csv / report_after.csv.


RG, Founder, Appie.run

Top comments (0)