DEV Community

appierun
appierun

Posted on

Audit LocalBusiness JSON-LD and NAP Consistency Across a Sitemap with Python (Standard Library Only): Wrong Phones, Name Drift

If you build sites for local businesses, the name, address and phone number (NAP) end up in a lot of places: the footer, the contact page, each location page, and the LocalBusiness JSON-LD that a plugin or template adds to the head. They start out matching. Then the client changes phone provider, a developer pastes the legal company name into one template, a new location page goes live without markup, and an old blog template keeps the number from two years ago.

None of that breaks the page. It only shows up when a customer calls a dead number or someone finally opens the Rich Results Test on the right URL.

This post builds a small auditor in Python using only the standard library (urllib, urllib.robotparser, xml.etree, html.parser, json, csv, concurrent.futures). You give it a sitemap and a short JSON file with each location's correct details (copy them from the client's Business Profile). It fetches every page and flags:

  • JSON-LD blocks that do not parse
  • location pages with no LocalBusiness markup
  • markup whose name, phone or address does not match the reference
  • phone numbers in the page text that belong to no location
  • phone numbers and street addresses that are in the markup but not on the page
  • missing required properties, incomplete addresses, phones without a country code and coordinates with too few decimals

It also prints every variant of each location's name, phone and address it found, and writes a CSV with one row per URL.

Sources opened on 23 Nov 2026: Google's LocalBusiness structured data documentation (showing "Last updated 2026-09-08 UTC"), Google's general structured data guidelines (showing "Last updated 2026-07-10 UTC"), the Google Business Profile guidelines for representing your business, Google's help page on improving local ranking, and schema.org/LocalBusiness (schema.org version 30.1). Every statement attributed to them below comes from those pages. The output in this post comes from a fictional three-location plumbing company ("Copperline Plumbing") served on localhost, built for this article with planted problems. Its phone numbers use the 555-01xx range set aside for fiction. Appie free-tool descriptions are as of 23 Nov 2026, checked on the tool's page that day.

Disclosure: Appie.run publishes this article. One free tool mentioned near the end is ours. The script does not depend on it.

Where this fits

This is another script in a small standard-library series that reads a sitemap and checks one thing per page. An earlier post showed how to extract and check JSON-LD structured data on a single page: does it parse, which types are there. This one goes a step further for local sites. It looks only at LocalBusiness nodes, compares them with the business's real details, and compares them with what the page shows to visitors.

What the guidance actually says

Google's LocalBusiness documentation. Only two properties are required: name and address. For address, Google says to "Include as many properties as possible." For telephone, it describes "A business phone number meant to be the primary contact method for customers" and adds: "Be sure to include the country code and area code in the phone number." For geo.latitude and geo.longitude: "The precision must be at least 5 decimal places." It also says to "Use the most specific LocalBusiness sub-type possible," and that you "can add LocalBusiness structured data to any page on your site, though it may make more sense to put it on a page that contains information about your business."

Google's general structured data guidelines. Two lines matter most here: "Provide up-to-date information" and "Don't mark up content that is not visible to readers of the page."

Business Profile guidelines. Google asks owners to "Represent your business as it's consistently represented and recognized in the real world across signage, stationery, and other branding." On names: "Your name should reflect your business's real-world name, as used consistently on your storefront, website, stationery, and as known to customers." Its list of things not to add to a profile name includes "irrelevant legal terms (e.g. LLC, LTD, INC)" unless they are part of the real-world name.

Local ranking. Google's local ranking help page says "Businesses with complete and accurate info are more likely to show up in local search results." That page is about the Business Profile itself, not website markup, so do not read it as a promise about JSON-LD. The practical point for an agency is simpler: the website should not contradict the profile.

schema.org. LocalBusiness is "A particular physical business or branch of an organization." It has many subtypes (Dentist, HomeAndConstructionBusiness, FoodEstablishment and so on), and those have their own subtypes, such as Plumber under HomeAndConstructionBusiness. A script that only looks for the literal string LocalBusiness will miss most real markup.

How the audit works

  1. Load the reference file: one entry per location with the correct name, address parts, phone and location page URL.
  2. Read the sitemap (or every child sitemap in an index), then robots.txt, and skip disallowed URLs.
  3. Fetch each page. One html.parser pass collects the JSON-LD blocks, the visible text (skipping script, style, noscript and template) and every tel: link.
  4. Parse each JSON-LD block, walk every nested object (so @graph and nested nodes work), and keep nodes whose @type is LocalBusiness or a known subtype.
  5. Match each node to a reference location: by url, then by @id, then by street address, then by phone.
  6. Compare and check. Phone numbers are compared as digits with the country code added. Addresses are compared part by part after lowercasing, removing punctuation and shortening common words ("Street" to "st", "Suite" to "ste"), so 418 Alder Street, Suite 2 and 418 Alder St Ste 2 count as the same.
  7. Print flagged pages (most serious first), totals, the variants per location, and write a CSV.

What the script flags

  • jsonld_parse_error: Severity: 1; Meaning: A JSON-LD block is not valid JSON, so nothing in it is read; Usual fix: Fix the syntax (often a stray or trailing comma)
  • missing_localbusiness: Severity: 1; Meaning: A page under a path you pass with --expect has no LocalBusiness node; Usual fix: Add markup to the location template
  • name_mismatch: Severity: 1; Meaning: Markup name differs from the reference; Usual fix: Use the real-world name from the profile
  • phone_mismatch: Severity: 1; Meaning: Markup telephone differs from the reference; Usual fix: Update the hard-coded number
  • address_mismatch: Severity: 1; Meaning: One or more address parts differ; Usual fix: Fix the typo or the old address
  • unknown_location: Severity: 1; Meaning: A LocalBusiness node matches no reference location; Usual fix: Add the location, or remove stale markup
  • unknown_phone_visible: Severity: 1; Meaning: The page text shows a number that belongs to no location; Usual fix: Find the old template or widget
  • missing_required: Severity: 2; Meaning: No name or no address; Usual fix: Add it
  • address_incomplete: Severity: 2; Meaning: Missing street, town, region, postal code or country, or address is plain text; Usual fix: Fill in the PostalAddress
  • phone_missing: Severity: 2; Meaning: No telephone; Usual fix: Add the location's main number
  • phone_not_visible: Severity: 2; Meaning: Markup phone does not appear in the page text; Usual fix: Show it, or fix the markup
  • address_not_visible: Severity: 2; Meaning: Markup street address does not appear in the page text; Usual fix: Show it, or fix the markup
  • phone_no_country_code: Severity: 3; Meaning: telephone does not start with +; Usual fix: Write it as +1-503-555-0142
  • geo_precision: Severity: 3; Meaning: Latitude or longitude has fewer than 5 decimals; Usual fix: Use the coordinates from the map pin

Non-HTML URLs in the sitemap (an llms.txt, a PDF) are listed as not_html and skipped.

The reference file

Save the correct details as locations.json. Copy them from the Business Profile, not from the website, because the website is what you are checking.

[
  {"id": "millbrook", "name": "Copperline Plumbing", "streetAddress": "418 Alder St Ste 2",
   "addressLocality": "Millbrook", "addressRegion": "OR", "postalCode": "97901", "addressCountry": "US",
   "telephone": "+1 503-555-0142", "url": "http://localhost:8783/locations/millbrook/"},
  {"id": "eastport", "name": "Copperline Plumbing", "streetAddress": "77 Harbor Rd",
   "addressLocality": "Eastport", "addressRegion": "OR", "postalCode": "97902", "addressCountry": "US",
   "telephone": "+1 503-555-0187", "url": "http://localhost:8783/locations/eastport/"},
  {"id": "riverside", "name": "Copperline Plumbing", "streetAddress": "9 Mill Pond Way",
   "addressLocality": "Riverside", "addressRegion": "OR", "postalCode": "97903", "addressCountry": "US",
   "telephone": "+1 503-555-0163", "url": "http://localhost:8783/locations/riverside/"}
]
Enter fullscreen mode Exit fullscreen mode

For a single-location business, the file has one entry. For a client with ten branches, it is ten entries, and you can keep one file per client next to your other onboarding notes.

The script

Save as local_nap_audit.py. Python 3.8 or later, nothing to install.

#!/usr/bin/env python3
"""Audit LocalBusiness JSON-LD and NAP (name, address, phone) consistency
across every page in a sitemap. Standard library only.

Usage:
  python3 local_nap_audit.py SITEMAP_URL --locations locations.json
      [--expect /locations/] [--country-code 1] [--csv nap_report.csv]
      [--workers 4] [--type Plumber] [--user-agent ...]
"""
import argparse, csv, json, re, sys
import urllib.request, urllib.robotparser, urllib.error
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit

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

# LocalBusiness, its direct schema.org subtypes and common deeper ones.
# Add your own with --type.
LOCAL_TYPES = {
    "LocalBusiness", "AnimalShelter", "ArchiveOrganization", "AutomotiveBusiness", "ChildCare",
    "Dentist", "DryCleaningOrLaundry", "EmergencyService", "EmploymentAgency",
    "EntertainmentBusiness", "FinancialService", "FoodEstablishment", "GovernmentOffice",
    "HealthAndBeautyBusiness", "HomeAndConstructionBusiness", "InternetCafe", "LegalService",
    "Library", "LodgingBusiness", "MedicalBusiness", "ProfessionalService", "RadioStation",
    "RealEstateAgent", "RecyclingCenter", "SelfStorage", "ShoppingCenter",
    "SportsActivityLocation", "Store", "TelevisionStation", "TouristInformationCenter",
    "TravelAgency",
    "Plumber", "Electrician", "HVACBusiness", "Locksmith", "RoofingContractor",
    "GeneralContractor", "HousePainter", "MovingCompany", "Restaurant", "CafeOrCoffeeShop",
    "Bakery", "BarOrPub", "HairSalon", "BeautySalon", "DaySpa", "NailSalon", "HealthClub",
    "AutoRepair", "AutoDealer", "Attorney", "Notary", "AccountingService", "InsuranceAgency",
    "VeterinaryCare", "Hotel", "Optician", "Physician", "MedicalClinic",
}

SEVERITY = {
    "jsonld_parse_error": 1, "missing_localbusiness": 1, "name_mismatch": 1,
    "phone_mismatch": 1, "address_mismatch": 1, "unknown_location": 1,
    "unknown_phone_visible": 1,
    "missing_required": 2, "address_incomplete": 2, "phone_missing": 2,
    "phone_not_visible": 2, "address_not_visible": 2,
    "phone_no_country_code": 3, "geo_precision": 3,
}

ADDRESS_PARTS = ["streetAddress", "addressLocality", "addressRegion", "postalCode", "addressCountry"]

# Common US street words. Extend for your market.
ABBR = {
    "street": "st", "avenue": "ave", "av": "ave", "road": "rd", "drive": "dr", "lane": "ln",
    "boulevard": "blvd", "court": "ct", "place": "pl", "parkway": "pkwy", "highway": "hwy",
    "suite": "ste", "unit": "ste", "apartment": "apt", "floor": "fl", "building": "bldg",
    "north": "n", "south": "s", "east": "e", "west": "w",
}

PHONE_RE = re.compile(r"(?<![\w+])(?:\+\d{1,3}[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?!\w)")


def fetch(url, ua, timeout=20):
    req = urllib.request.Request(url, headers={"User-Agent": ua})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ctype = r.headers.get("Content-Type", "")
            return r.status, ctype, r.read(3_000_000).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, "", ""
    except Exception as e:
        return 0, "", str(e)


def sitemap_urls(url, ua, seen=None):
    seen = seen if seen is not None else set()
    if url in seen:
        return []
    seen.add(url)
    status, _, body = fetch(url, ua)
    if status != 200:
        print(f"Could not read sitemap {url} (status {status})", file=sys.stderr)
        return []
    root = ET.fromstring(body.encode())
    if root.tag == SM_NS + "sitemapindex":
        out = []
        for loc in root.iter(SM_NS + "loc"):
            out += sitemap_urls(loc.text.strip(), ua, seen)
        return out
    return [loc.text.strip() for loc in root.iter(SM_NS + "loc") if loc.text]


# ---------- normalising ----------

def norm_phone(raw, cc):
    """Return digits with country code, e.g. '+1 (503) 555-0142' -> '15035550142'."""
    raw = str(raw).strip()
    if raw.lower().startswith("tel:"):
        raw = raw[4:]
    d = re.sub(r"\D", "", raw)
    if not d:
        return ""
    if raw.startswith("+"):
        return d
    if d.startswith("00"):
        return d[2:]
    if cc == "1" and len(d) == 11 and d.startswith("1"):
        return d
    if d.startswith("0"):          # national trunk prefix, e.g. UK 020...
        d = d[1:]
    return cc + d


def national(digits, cc):
    return digits[len(cc):] if digits.startswith(cc) else digits


def norm_text(s):
    s = str(s).casefold().replace("&", " and ")
    words = re.sub(r"[^\w\s]", " ", s).split()
    return " ".join(ABBR.get(w, w) for w in words)


def norm_name(s):
    return " ".join(str(s).casefold().split())


# ---------- page parsing ----------

class PageParser(HTMLParser):
    SKIP = {"script", "style", "noscript", "template"}

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.jsonld, self.text, self.tel = [], [], []
        self._ld = None
        self._skip = 0

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "script" and (a.get("type") or "").split(";")[0].strip().lower() == "application/ld+json":
            self._ld = []
            return
        if tag in self.SKIP:
            self._skip += 1
        if tag == "a" and (a.get("href") or "").lower().startswith("tel:"):
            self.tel.append(a["href"])

    def handle_endtag(self, tag):
        if tag == "script" and self._ld is not None:
            self.jsonld.append("".join(self._ld))
            self._ld = None
            return
        if tag in self.SKIP and self._skip:
            self._skip -= 1

    def handle_data(self, data):
        if self._ld is not None:
            self._ld.append(data)
        elif not self._skip and data.strip():
            self.text.append(data.strip())


def types_of(node):
    t = node.get("@type", [])
    t = t if isinstance(t, list) else [t]
    return {str(x).rsplit("/", 1)[-1] for x in t}


def walk(obj):
    if isinstance(obj, dict):
        yield obj
        for v in obj.values():
            yield from walk(v)
    elif isinstance(obj, list):
        for v in obj:
            yield from walk(v)


def decimals(value):
    s = str(value)
    return len(s.split(".", 1)[1]) if "." in s else 0


# ---------- the audit ----------

def match_location(node, refs, cc):
    url = (node.get("url") or "").rstrip("/")
    nid = (node.get("@id") or "").split("#")[0].rstrip("/")
    for r in refs:
        if url and url == r["url"].rstrip("/"):
            return r
        if nid and nid == r["url"].rstrip("/"):
            return r
    addr = node.get("address")
    if isinstance(addr, dict) and addr.get("streetAddress"):
        s = norm_text(addr["streetAddress"])
        for r in refs:
            if s == norm_text(r["streetAddress"]):
                return r
    if node.get("telephone"):
        p = norm_phone(node["telephone"], cc)
        for r in refs:
            if p == norm_phone(r["telephone"], cc):
                return r
    return None


def audit_page(url, refs, args, local_types):
    issues, seen = [], defaultdict(list)

    def flag(code, detail):
        issues.append((code, detail))

    status, ctype, body = fetch(url, args.user_agent)
    if status != 200 or "html" not in ctype.lower():
        return {"url": url, "status": status, "nodes": 0, "issues": [("not_html", ctype or body[:80])], "seen": seen}

    p = PageParser()
    p.feed(body)
    visible = " ".join(p.text)
    visible_norm = norm_text(visible)
    visible_digits = [re.sub(r"\D", "", t) for t in p.text] + [re.sub(r"\D", "", t) for t in p.tel]
    visible_phones = {norm_phone(m, args.country_code) for m in PHONE_RE.findall(visible)}
    visible_phones |= {norm_phone(t, args.country_code) for t in p.tel}
    known_phones = {norm_phone(r["telephone"], args.country_code) for r in refs}

    nodes = []
    for i, raw in enumerate(p.jsonld, 1):
        try:
            data = json.loads(raw, parse_float=str)   # keep 45.50000 as written
        except json.JSONDecodeError as e:
            flag("jsonld_parse_error", f"block {i}: {e.msg} at line {e.lineno} col {e.colno}")
            continue
        nodes += [n for n in walk(data) if types_of(n) & local_types]

    path = urlsplit(url).path
    if not nodes and any(path.startswith(x) for x in args.expect) and path not in args.expect:
        flag("missing_localbusiness", f"no LocalBusiness markup on a page under {', '.join(args.expect)}")

    for n in nodes:
        label = "/".join(sorted(types_of(n) & local_types))
        name, phone, addr = n.get("name"), n.get("telephone"), n.get("address")
        if not name or not addr:
            flag("missing_required", f"{label} without {'name' if not name else 'address'}")
        ref = match_location(n, refs, args.country_code)
        if ref is None:
            flag("unknown_location", f"{label} '{name}' does not match any location in the reference file")
        else:
            seen[ref["id"], "name"].append(str(name))
        if ref and name and norm_name(name) != norm_name(ref["name"]):
            flag("name_mismatch", f"'{name}' (reference: '{ref['name']}')")

        if not phone:
            flag("phone_missing", f"{label} has no telephone")
        else:
            np_ = norm_phone(phone, args.country_code)
            if ref:
                seen[ref["id"], "telephone"].append(str(phone))
            if not str(phone).strip().startswith("+"):
                flag("phone_no_country_code", f"'{phone}'")
            if ref and np_ != norm_phone(ref["telephone"], args.country_code):
                flag("phone_mismatch", f"'{phone}' (reference: '{ref['telephone']}')")
            nat = national(np_, args.country_code)
            if nat and not any(nat in d for d in visible_digits):
                flag("phone_not_visible", f"'{phone}' is in the markup but not in the page text")

        if isinstance(addr, dict):
            missing = [k for k in ADDRESS_PARTS if not addr.get(k)]
            if missing:
                flag("address_incomplete", "missing " + ", ".join(missing))
            if ref:
                seen[ref["id"], "address"].append(", ".join(str(addr.get(k, "")) for k in ADDRESS_PARTS if addr.get(k)))
                diff = [f"{k} '{addr[k]}' vs '{ref[k]}'" for k in ADDRESS_PARTS
                        if addr.get(k) and norm_text(addr[k]) != norm_text(ref[k])]
                if diff:
                    flag("address_mismatch", "; ".join(diff))
            street = addr.get("streetAddress")
            if street and norm_text(street) not in visible_norm:
                flag("address_not_visible", f"'{street}' is in the markup but not in the page text")
        elif isinstance(addr, str):
            flag("address_incomplete", "address is plain text, not a PostalAddress")

        geo = n.get("geo")
        if isinstance(geo, dict):
            for k in ("latitude", "longitude"):
                if geo.get(k) is not None and decimals(geo[k]) < 5:
                    flag("geo_precision", f"{k} {geo[k]} has {decimals(geo[k])} decimals (Google asks for at least 5)")

    if refs:
        for ph in sorted(visible_phones - known_phones):
            flag("unknown_phone_visible", f"page shows +{ph}, which is not in the reference file")
    for ph in visible_phones:
        seen["(page text)", "telephone"].append("+" + ph)
    return {"url": url, "status": status, "nodes": len(nodes), "issues": issues, "seen": seen}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("sitemap")
    ap.add_argument("--locations", required=True, help="JSON list of reference locations (your Business Profile data)")
    ap.add_argument("--expect", action="append", default=[], help="path prefix whose pages must carry LocalBusiness markup (repeatable)")
    ap.add_argument("--country-code", default="1", help="country calling code for numbers written without one (default 1)")
    ap.add_argument("--type", action="append", default=[], help="extra schema.org type to treat as a local business")
    ap.add_argument("--csv", default="nap_report.csv")
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--user-agent", default=UA)
    args = ap.parse_args()

    with open(args.locations, encoding="utf-8") as f:
        refs = json.load(f)
    local_types = LOCAL_TYPES | set(args.type)

    urls = list(dict.fromkeys(sitemap_urls(args.sitemap, args.user_agent)))
    rp = urllib.robotparser.RobotFileParser(urljoin(args.sitemap, "/robots.txt"))
    try:
        rp.read()
        allowed = [u for u in urls if rp.can_fetch(args.user_agent, u)]
    except Exception:
        allowed = urls
    print(f"Sitemap URLs: {len(urls)}  allowed by robots.txt: {len(allowed)}  reference locations: {len(refs)}")

    with ThreadPoolExecutor(max_workers=args.workers) as ex:
        results = list(ex.map(lambda u: audit_page(u, refs, args, local_types), allowed))

    flagged = [r for r in results if r["issues"]]
    marked = sum(1 for r in results if r["nodes"])
    print(f"Pages with LocalBusiness markup: {marked} of {len(results)}")
    print(f"Pages with NAP issues: {len(flagged)} of {len(results)}\n")
    flagged.sort(key=lambda r: (min(SEVERITY.get(c, 9) for c, _ in r["issues"]), r["url"]))
    totals = Counter()
    for r in flagged:
        print(r["url"])
        for code, detail in sorted(r["issues"], key=lambda x: SEVERITY.get(x[0], 9)):
            print(f"  [{code}] {detail}")
            totals[code] += 1
    if totals:
        print("\nTotals: " + ", ".join(f"{k} {v}" for k, v in sorted(totals.items(), key=lambda x: (SEVERITY.get(x[0], 9), x[0]))))

    variants = defaultdict(Counter)
    for r in results:
        for key, vals in r["seen"].items():
            variants[key].update(vals)
    print("\nNAP variants found in markup, per reference location:")
    for ref in refs:
        for field in ("name", "telephone", "address"):
            c = variants.get((ref["id"], field))
            if c:
                vals = "; ".join(f"'{v}' x{n}" for v, n in c.most_common())
                print(f"  {ref['id']:<10} {field:<9} {len(c)} variant{'s' if len(c) > 1 else ''}: {vals}")
    vis = variants.get(("(page text)", "telephone"), Counter())
    print("Phone numbers in page text: " + "; ".join(f"{v} on {n} page{'s' if n > 1 else ''}" for v, n in vis.most_common()))

    with open(args.csv, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["url", "status", "localbusiness_nodes", "issues"])
        for r in results:
            w.writerow([r["url"], r["status"], r["nodes"], "; ".join(f"{c}: {d}" for c, d in r["issues"])])
    print(f"\nCSV written: {args.csv}")


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

A few choices worth knowing about:

  • json.loads(raw, parse_float=str) keeps numbers as they were written. With normal float parsing, 45.50000 becomes 45.5 and the decimal check would report 1 decimal instead of 5.
  • The phone-in-text check compares digits only, per text node and per tel: link, so (503) 555-0142, 503.555.0142 and +1 503 555 0142 all count as the same number.
  • PHONE_RE, which finds phone numbers in the page text for unknown_phone_visible, is written for North American formats. For other countries, adjust it (or rely on tel: links, which are always read). --country-code 44 handles numbers written with a leading 0, such as UK numbers.
  • ABBR only knows common US street words. Add your market's words before trusting address_mismatch outside the US.

The test site

The fixture is a fictional plumbing company with three locations, served by python3 -m http.server on port 8783. Nine pages: home, three location pages, two service pages, contact, about, and one blog post. Every page has a footer showing the main office's name, address and phone.

Planted problems:

  • /about/ has a stray extra comma in its JSON-LD.
  • /locations/riverside/ is a new location page that went live without markup.
  • /contact/ uses the legal name "Copperline Plumbing & Heating LLC" in its markup.
  • /services/water-heaters/ has the company's old number hard-coded in its markup.
  • /services/drain-cleaning/ spells the town "Milbrook".
  • /locations/eastport/ writes the phone without a country code, leaves out the postal code and uses 3-decimal coordinates.
  • /blog/winterize-your-pipes/ uses an older template whose footer still shows the old number.

Two things are deliberately fine and should not be flagged: /locations/millbrook/ wraps its node in an @graph with a WebPage, and writes the street as "418 Alder Street, Suite 2" while the reference says "418 Alder St Ste 2".

Running it

python3 local_nap_audit.py http://localhost:8783/sitemap.xml \
  --locations locations.json \
  --expect /locations/ \
  --csv nap_report_before.csv
Enter fullscreen mode Exit fullscreen mode

Output:

Sitemap URLs: 9  allowed by robots.txt: 9  reference locations: 3
Pages with LocalBusiness markup: 6 of 9
Pages with NAP issues: 7 of 9

http://localhost:8783/about/
  [jsonld_parse_error] block 1: Expecting property name enclosed in double quotes at line 6 col 32
http://localhost:8783/blog/winterize-your-pipes/
  [unknown_phone_visible] page shows +15035550119, which is not in the reference file
http://localhost:8783/contact/
  [name_mismatch] 'Copperline Plumbing & Heating LLC' (reference: 'Copperline Plumbing')
http://localhost:8783/locations/riverside/
  [missing_localbusiness] no LocalBusiness markup on a page under /locations/
http://localhost:8783/services/drain-cleaning/
  [address_mismatch] addressLocality 'Milbrook' vs 'Millbrook'
http://localhost:8783/services/water-heaters/
  [phone_mismatch] '+1-503-555-0119' (reference: '+1 503-555-0142')
  [phone_not_visible] '+1-503-555-0119' is in the markup but not in the page text
http://localhost:8783/locations/eastport/
  [address_incomplete] missing postalCode
  [phone_no_country_code] '(503) 555-0187'
  [geo_precision] latitude 45.488 has 3 decimals (Google asks for at least 5)
  [geo_precision] longitude -122.604 has 3 decimals (Google asks for at least 5)

Totals: address_mismatch 1, jsonld_parse_error 1, missing_localbusiness 1, name_mismatch 1, phone_mismatch 1, unknown_phone_visible 1, address_incomplete 1, phone_not_visible 1, geo_precision 2, phone_no_country_code 1

NAP variants found in markup, per reference location:
  millbrook  name      2 variants: 'Copperline Plumbing' x4; 'Copperline Plumbing & Heating LLC' x1
  millbrook  telephone 2 variants: '+1-503-555-0142' x4; '+1-503-555-0119' x1
  millbrook  address   3 variants: '418 Alder St, Suite 2, Millbrook, OR, 97901, US' x3; '418 Alder Street, Suite 2, Millbrook, OR, 97901, US' x1; '418 Alder St, Suite 2, Milbrook, OR, 97901, US' x1
  eastport   name      1 variant: 'Copperline Plumbing' x1
  eastport   telephone 1 variant: '(503) 555-0187' x1
  eastport   address   1 variant: '77 Harbor Rd, Eastport, OR, US' x1
Phone numbers in page text: +15035550142 on 8 pages; +15035550187 on 2 pages; +15035550163 on 2 pages; +15035550119 on 1 page

CSV written: nap_report_before.csv
Enter fullscreen mode Exit fullscreen mode

Things to notice:

  • The water heater page shows two flags for one cause. The old number is wrong (phone_mismatch), and because the footer shows the right number, the wrong one appears nowhere on the page (phone_not_visible). Google's guidelines ask you not to mark up content readers cannot see, so the second flag is worth reading even when the first is fixed.
  • The blog post has no LocalBusiness markup and none is expected, but its footer still shows the old number. Only the page-text check catches this, and it is the one a customer would actually dial.
  • The about page's markup is skipped entirely because the block does not parse. That is why the variant list counts 5 Millbrook nodes in the first run and 6 after the fix. A parse error hides every other problem in that block, so fix those first.
  • The variant list shows "418 Alder St" and "418 Alder Street" as separate address strings, but neither is flagged. The script reports formatting variants so you can tidy them, and flags only real differences.
  • The Millbrook location page passes even though its node sits inside an @graph.

The CSV has one row per URL:

url,status,localbusiness_nodes,issues
http://localhost:8783/,200,1,
http://localhost:8783/locations/millbrook/,200,1,
http://localhost:8783/locations/eastport/,200,1,phone_no_country_code: '(503) 555-0187'; address_incomplete: missing postalCode; geo_precision: latitude 45.488 has 3 decimals (Google asks for at least 5); geo_precision: longitude -122.604 has 3 decimals (Google asks for at least 5)
http://localhost:8783/locations/riverside/,200,0,missing_localbusiness: no LocalBusiness markup on a page under /locations/
http://localhost:8783/services/water-heaters/,200,1,phone_mismatch: '+1-503-555-0119' (reference: '+1 503-555-0142'); phone_not_visible: '+1-503-555-0119' is in the markup but not in the page text
http://localhost:8783/services/drain-cleaning/,200,1,address_mismatch: addressLocality 'Milbrook' vs 'Millbrook'
http://localhost:8783/contact/,200,1,name_mismatch: 'Copperline Plumbing & Heating LLC' (reference: 'Copperline Plumbing')
http://localhost:8783/about/,200,0,jsonld_parse_error: block 1: Expecting property name enclosed in double quotes at line 6 col 32
http://localhost:8783/blog/winterize-your-pipes/,200,0,"unknown_phone_visible: page shows +15035550119, which is not in the reference file"
Enter fullscreen mode Exit fullscreen mode

Fixing it and running again

The fixes on the test site:

  • /about/: removed the extra comma.
  • /locations/riverside/: added a Plumber node built from the reference entry.
  • /contact/: changed the markup name to "Copperline Plumbing", the name on the profile and the storefront.
  • /services/water-heaters/ and /services/drain-cleaning/: replaced the hard-coded nodes with the same Millbrook node the home page uses.
  • /locations/eastport/: +1-503-555-0187, added the postal code, and used 5-decimal coordinates.
  • /blog/winterize-your-pipes/: moved the blog to the current footer.

Second run:

python3 local_nap_audit.py http://localhost:8783/sitemap.xml \
  --locations locations.json \
  --expect /locations/ \
  --csv nap_report_after.csv
Enter fullscreen mode Exit fullscreen mode
Sitemap URLs: 9  allowed by robots.txt: 9  reference locations: 3
Pages with LocalBusiness markup: 8 of 9
Pages with NAP issues: 0 of 9


NAP variants found in markup, per reference location:
  millbrook  name      1 variant: 'Copperline Plumbing' x6
  millbrook  telephone 1 variant: '+1-503-555-0142' x6
  millbrook  address   2 variants: '418 Alder St, Suite 2, Millbrook, OR, 97901, US' x5; '418 Alder Street, Suite 2, Millbrook, OR, 97901, US' x1
  eastport   name      1 variant: 'Copperline Plumbing' x1
  eastport   telephone 1 variant: '+1-503-555-0187' x1
  eastport   address   1 variant: '77 Harbor Rd, Eastport, OR, 97902, US' x1
  riverside  name      1 variant: 'Copperline Plumbing' x1
  riverside  telephone 1 variant: '+1-503-555-0163' x1
  riverside  address   1 variant: '9 Mill Pond Way, Riverside, OR, 97903, US' x1
Phone numbers in page text: +15035550142 on 9 pages; +15035550187 on 2 pages; +15035550163 on 2 pages

CSV written: nap_report_after.csv
Enter fullscreen mode Exit fullscreen mode

Each location now has one name and one phone across the site, and the only address variant left is spelling ("St" or "Street"), which the script treats as the same address.

Running it on a client site

  • Start from the profile. Fill locations.json from the Business Profile. If the profile itself is out of date, fix that first, or the audit will push the website toward the wrong details.
  • Use --expect for location pages. Pass every path prefix where each page should carry markup, such as --expect /locations/ --expect /areas/. Leave out pages like the blog, where markup is optional.
  • Add your types. If the client's markup uses a type the script does not list (for example ComputerStore, a subtype of Store; the script matches exact type names, not the type tree), pass --type ComputerStore. Unlisted types are silently ignored, so check the CSV's localbusiness_nodes column for pages you expected to count.
  • Service-area businesses. If the client hides its address on the profile, the reference address may be empty and address_incomplete will fire. Decide with the client what the site should show, then adjust the reference or ignore that flag.
  • JavaScript-rendered markup. The script reads the HTML the server sends. If a tag manager or a script injects the JSON-LD in the browser, the page will look unmarked. Check one such page with Google's Rich Results Test before trusting a missing_localbusiness flag.
  • Hidden text. The script does not read CSS, so a phone number in a display: none block counts as visible. It does skip script, style, noscript and template.
  • Departments. Google's documentation describes nesting departments, each with its own phone number, inside the main node. The script checks nested nodes too, and a department at the same street address is matched to the main location, so its own number shows up as phone_mismatch. Add each department to the reference file with its own url, or treat those flags as expected.
  • Be polite. The default is 4 workers. Use --workers 2 on small shared hosting.

The script checks consistency, not eligibility. Google's documentation still asks you to validate with the Rich Results Test, and the same page says "Google does not guarantee that features that consume structured data will show up in search results."

What to fix first

  1. Wrong phone numbers anywhere (phone_mismatch, unknown_phone_visible). These cost the client calls.
  2. Parse errors. One bad comma hides everything else in the block.
  3. Missing markup on location pages. Usually a template fix covers all of them.
  4. Name and address mismatches. Usually one hard-coded node; replace it with the shared one.
  5. Visibility, completeness and format. Lower risk, quick to clear once the template is right.

Related free tool

Before you audit a new client's site, you need to know where its sitemap lives. Our free Sitemap Finder and Checker takes a site URL, reads robots.txt and the usual sitemap paths, and reports which sitemap files load and how many URLs they list. It does not look at structured data; that is what the script is for.

FAQ

What does NAP mean?
Name, address and phone number. For a local business, those three details should read the same on the website, in its structured data and on its Business Profile.

Which LocalBusiness properties does Google require?
Google's LocalBusiness documentation lists name and address as required. telephone, geo, url, openingHoursSpecification and others are recommended.

Should the phone number in JSON-LD include the country code?
Yes. Google's documentation says to "include the country code and area code in the phone number."

Can I put LocalBusiness markup on every page?
Google says you can add it to any page, "though it may make more sense to put it on a page that contains information about your business." If you do add it site-wide, generate it from one source so it cannot drift, and make sure the details are visible on the page.

Does "Street" versus "St" count as inconsistent?
Not in this script. It compares addresses after shortening common words and removing punctuation. It does list both spellings in the variant summary so you can standardize them if you want.

Will fixing NAP improve local rankings?
The script cannot tell you that. Google's local ranking help page says businesses with complete and accurate info on their Business Profile are more likely to show up in local results. Treat the website audit as making sure the site does not contradict the profile, and as keeping customers away from dead numbers.


If you are onboarding a new local client, our free Sitemap Finder and Checker finds their sitemap in one step, so you can point this script at it.

RG, Founder, Appie.run

Top comments (0)