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 AnalyticsUA-, Tag ManagerGTM-, Google AdsAW-, and Meta Pixel IDs fromfbq('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:
- 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.
- 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. - 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 anhttp://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() 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 ingtag('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 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 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 ...
