Yellow Pages Scraper GitHub: How to Run a Local Market Saturation Analysis with Python
You can measure how saturated a local market is — category by category, city by city — by collecting public business directory records and computing density, concentration, and coverage-gap metrics on top of them. No paid market research report needed for the first pass. This guide is for franchise development teams, local marketing agencies, and market researchers who need to answer a specific question before committing budget: "how crowded is this territory, and where are the gaps?"
The workflow below uses two repositories from the data-scrape account: a Yellow Pages scraper that collects public directory business records, and a Google Maps scraper you can pair with it to cross-check local business coverage. The repositories handle collection; the analysis in this article — the part most teams skip — is where the decision value lives.
TL;DR
- Collect public directory records for your target category across the ZIP codes or cities you care about.
- Normalize every record to the same schema: business name, category, city, ZIP, phone, rating, review count.
- Compute four metrics per market: listing density, category concentration (how dominant the top players are), review-weighted competition, and coverage gaps (target areas with zero or thin listings).
- Score each territory, rank them, and use the gap list to prioritize expansion or campaign targeting.
- Run it on a schedule so the picture stays current instead of going stale in a deck.
Everything below runs on public records only. You still need to respect the directory's terms and applicable privacy law — details in the compliance section.
Why this is harder than it looks
The obvious approach is to open the directory, browse a few cities, and count listings by eye. That fails in three predictable ways:
Inconsistent geography. One analyst counts "Austin" as the city limits, another includes Round Rock and Cedar Park. Your saturation numbers are not comparable if the geographies drift between runs.
Category drift. "Plumber," "Plumbing Contractors," and "Plumbing" may all appear for similar businesses. Without normalization, one category splits into three and every density number is wrong.
No repeatability. A manual count is a snapshot in someone's browser. Two weeks later you cannot answer "what changed?" because there is no underlying dataset — just impressions.
The fix is boring and effective: one normalized record set per geography, collected the same way every time, with analysis code that runs on top of it. Once the pipeline exists, re-running it monthly is nearly free.
The workflow
The pipeline has four stages:
- Collect. For each target geography and category, gather public directory records. The Yellow Pages directory scraper returns business records for a location and category query; check its README for the current invocation method and output fields before you build on it.
-
Normalize. Map every record into one schema:
name,category,city,zip,phone,rating,review_count. Collapse category variants with a small mapping table you own and can audit. - Analyze. Compute per-market metrics and rank territories.
- Cross-check (optional but recommended). Run the same target list through a Google Maps business data scraper and compare coverage. If one source shows a gap and the other does not, you have found either a real gap or a coverage difference worth knowing about — both are useful.
A practical note on expectations: directory coverage varies by category and region. A saturation analysis built on one public source is a screening tool that tells you where to look harder, not a census. That is exactly what you want for territory shortlisting.
Setup
You need Python 3.9+ and the normalized record set. Collection credentials and endpoints are account-specific, so the analysis script reads them from environment variables and never hardcodes them:
# Example — copy the actual endpoint from the repository's README or console
export DIRECTORY_ENDPOINT="https://your-endpoint.example.com/search"
export DIRECTORY_API_KEY="your-key-here"
export FETCH_FROM_ENDPOINT="1" # set to "0" to run the script on the embedded sample records
If FETCH_FROM_ENDPOINT=1, the script fetches records from the endpoint you configured. If 0, it runs entirely on the embedded sample data below — which means you can verify the analysis logic before wiring up any collection.
The analysis script
This script is runnable as-is. It computes the four saturation metrics per market and prints a ranked scorecard:
import json
import os
import urllib.request
from collections import defaultdict
import statistics
# --- Configuration: no credentials or endpoints hardcoded ---
ENDPOINT = os.environ.get("DIRECTORY_ENDPOINT", "")
API_KEY = os.environ.get("DIRECTORY_API_KEY", "")
FETCH = os.environ.get("FETCH_FROM_ENDPOINT", "0") == "1"
# Target markets: (city, zip). Keep this list versioned — it defines your geography.
TARGET_MARKETS = [
("Austin", "78701"), ("Austin", "78704"),
("Round Rock", "78664"),
("Cedar Park", "78613"),
]
CATEGORY = "plumbing"
# Representative records in the normalized schema. Labeled as EXAMPLE data:
# replace with real collected records when FETCH=1.
SAMPLE_RECORDS = [
{"name": "Example Plumbing Co A", "category": "plumbing", "city": "Austin", "zip": "78701", "rating": 4.6, "review_count": 182},
{"name": "Example Plumbing Co B", "category": "plumbing", "city": "Austin", "zip": "78701", "rating": 4.2, "review_count": 64},
{"name": "Example Plumbing Co C", "category": "plumbing", "city": "Austin", "zip": "78704", "rating": 4.8, "review_count": 240},
{"name": "Example Plumbing Co D", "category": "plumbing", "city": "Austin", "zip": "78704", "rating": 3.9, "review_count": 31},
{"name": "Example Plumbing Co E", "category": "plumbing", "city": "Austin", "zip": "78704", "rating": 4.4, "review_count": 118},
{"name": "Example Plumbing Co F", "category": "plumbing", "city": "Round Rock", "zip": "78664", "rating": 4.7, "review_count": 156},
{"name": "Example Plumbing Co G", "category": "plumbing", "city": "Round Rock", "zip": "78664", "rating": 4.1, "review_count": 42},
# Cedar Park intentionally has no records in this example -> coverage gap
]
def fetch_records(category):
if not FETCH:
return SAMPLE_RECORDS
if not ENDPOINT or not API_KEY:
raise SystemExit("FETCH_FROM_ENDPOINT=1 requires DIRECTORY_ENDPOINT and DIRECTORY_API_KEY")
url = f"{ENDPOINT}?category={urllib.request.quote(category)}&per_market=200"
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {API_KEY}"})
with urllib.request.urlopen(req, timeout=60) as resp:
return json.load(resp)
def normalize(records):
out = []
for r in records:
out.append({
"name": r.get("name", "").strip(),
"category": CATEGORY_MAP.get(r.get("category", "").lower(), r.get("category", "").lower()),
"city": r.get("city", "").strip(),
"zip": r.get("zip", "").strip(),
"rating": float(r.get("rating") or 0),
"review_count": int(r.get("review_count") or 0),
})
return out
# Category variants you observed in the data -> one canonical label. Audit this table.
CATEGORY_MAP = {
"plumber": "plumbing",
"plumbing contractors": "plumbing",
"plumbing": "plumbing",
}
def analyze(records, targets, category):
by_market = defaultdict(list)
for r in records:
if r["category"] == category:
by_market[(r["city"], r["zip"])].append(r)
rows = []
for city, zc in targets:
recs = by_market.get((city, zc), [])
n = len(recs)
if n == 0:
rows.append({"city": city, "zip": zc, "listings": 0, "density_score": 0.0,
"top3_share": 0.0, "review_weighted": 0.0, "gap": True})
continue
# Density: listings per market, scaled against your max-observed later
density = n
# Concentration: share of total reviews held by the top 3 listings
reviews = sorted((r["review_count"] for r in recs), reverse=True)
total_reviews = sum(reviews) or 1
top3_share = sum(reviews[:3]) / total_reviews
# Review-weighted competition: how much established reputational mass exists
review_weighted = statistics.mean(reviews) * (statistics.mean([r["rating"] for r in recs]) or 0)
rows.append({"city": city, "zip": zc, "listings": n, "density_score": density,
"top3_share": round(top3_share, 2), "review_weighted": round(review_weighted, 1),
"gap": False})
return rows
def rank(rows, max_density):
"""Rank territories: low density + low review mass = opportunity; flag gaps."""
for row in rows:
if row["gap"]:
row["opportunity_score"] = 100.0 # zero coverage = widest-open gap
continue
density_ratio = row["density_score"] / max_density if max_density else 0
row["opportunity_score"] = round(100 * (1 - density_ratio) * (1 - row["top3_share"] * 0.5), 1)
return sorted(rows, key=lambda r: -r["opportunity_score"])
records = normalize(fetch_records(CATEGORY))
rows = analyze(records, TARGET_MARKETS, CATEGORY)
max_density = max((r["density_score"] for r in rows), default=0)
for r in rank(rows, max_density):
print(json.dumps(r))
Representative output
Running the script on the embedded sample data prints one ranked row per market (EXAMPLE output — your numbers will differ with real records):
{"city": "Cedar Park", "zip": "78613", "listings": 0, "density_score": 0.0, "top3_share": 0.0, "review_weighted": 0.0, "gap": true, "opportunity_score": 100.0}
{"city": "Austin", "zip": "78701", "listings": 2, "density_score": 2, "top3_share": 1.0, "review_weighted": 541.2, "gap": false, "opportunity_score": 16.7}
{"city": "Round Rock", "zip": "78664", "listings": 2, "density_score": 2, "top3_share": 1.0, "review_weighted": 435.6, "gap": false, "opportunity_score": 16.7}
{"city": "Austin", "zip": "78704", "listings": 3, "density_score": 3, "top3_share": 1.0, "review_weighted": 566.2, "gap": false, "opportunity_score": 0.0}
How to read it: Cedar Park shows a zero-coverage gap (verify against a second source before acting). Notice that every covered market's top-3 share is 1.0 — with only two or three listings, the top three always hold all review volume, so concentration only becomes informative once a market has more listings than that. Austin 78704 carries the most review-weighted mass and therefore the lowest opportunity score, which matches intuition: it is the densest, most reputationally established market in the sample. With real collection at 50+ records per market, the concentration metric separates consolidated from fragmented markets meaningfully.
The four metrics, in plain terms
- Listing density — raw count per market. Simple, but a market with 30 low-review listings is easier to enter than one with 5 dominant ones, so never read it alone.
- Top-3 review share — concentration. If three businesses hold 80% of review volume, that territory is consolidated; head-on positioning is expensive.
- Review-weighted competition — average review count times average rating. It approximates how much established trust a new entrant must overcome.
- Opportunity score — a rankable combination: low density and dispersed reviews push it up; zero coverage tops it out, pending cross-source verification.
For a deeper treatment of how public web data feeds market research generally, the Chinese-language public-web-data guide covers this workflow class in a market research web data guide.
Business use cases
- Franchise territory planning. Score candidate territories before paying for demographic overlays. The gap list tells your development team where category supply is thin.
- Local SEO and campaign targeting. Agencies can allocate client budget toward ZIP codes with low density and dispersed review mass instead of competing in consolidated markets.
- Competitive monitoring. Re-run monthly and diff the output. A new entrant with fast-growing review counts in a previously thin market is an early signal worth a human look.
- Product-line expansion. Run the same script with a different category string to compare saturation across verticals in the same geography.
One operational tip that saves hours later: keep each run's output as a dated JSONL file (saturation-YYYY-MM-DD.jsonl) rather than overwriting. The value of a screening scorecard compounds over time — three months of ranked rows tells you which markets are genuinely thin and stable versus which ones fluctuate with directory freshness. A ten-line Python diff between consecutive runs is enough to flag new entrants and disappearing listings without building a full time-series database.
Build vs. managed options
| Option | Best for | Maintenance burden | Notes |
|---|---|---|---|
| Manual browsing + spreadsheet | One-off, 3-5 markets | Low but not repeatable | Geography and category drift; no history |
| Self-built scraper | Unique needs, engineering capacity | High — layouts change | You own parsing, pacing, and retries |
| Repository-based collection (this workflow) | Repeatable screening across many markets | Moderate — re-verify output fields per run | Collection handled; analysis is yours |
| Managed data provider | Large-scale, ongoing extraction | Low | Verify current coverage and pricing on the provider's official pages |
Whichever route you take, the analysis layer above stays the same — that is the point of normalizing to one schema.
Limits, compliance, and maintenance
- Coverage is not a census. Public directories lag reality; new businesses may be missing and closed ones may linger. Cross-check headline findings with a second source before major commitments.
- Category mapping is an owned asset. Review your variant table when you add markets. A stale map silently corrupts density numbers.
- Respect the source. Collect only public business information, follow the directory's terms of service and robots directives, and pace your requests. Business contact details are still personal data under many privacy regimes — store only what your analysis needs, and honor removal requests where applicable.
- No invented guarantees. Neither repository promises a specific quota, price, or uptime. Confirm the current invocation details and any usage limits on the repository README or provider documentation before production runs.
- Maintenance rhythm. Re-verify output fields monthly; diff each run against the previous one and investigate any market whose listing count jumps by more than a threshold you set.
FAQ
Is there an official API for Yellow Pages data?
Not a public one you can rely on for analysis at scale, which is why repository-based collection of public records is the common route. Verify any current offering directly on official pages before building against it.
What fields does the workflow actually need?
Five: name, category, city/ZIP, rating, and review count. Phone is useful for deduplication but not required for the scoring math.
How often should the analysis run?
Monthly is enough for territory screening; weekly if you are actively monitoring competitive entry in a few markets.
What happens when the directory layout changes?
Collection breaks before analysis does — you will see empty or malformed records. That is why the script validates field presence during normalization and why you should diff run counts against the prior run.
Can this feed a CRM, dashboard, or AI agent?
Yes. The ranked output is plain JSON lines, so it loads into a spreadsheet, a BI tool, or an agent's context without transformation. For the AI-agent angle, keep the record set traceable — source, timestamp, and query parameters per batch.
Do I need both repositories?
No. The directory scraper alone runs the whole analysis. The Google Maps scraper earns its place as a cross-check on coverage gaps, which are the findings most likely to trigger expensive decisions.
What should I verify before production use?
The current endpoint and fields from the repository README, your target geography list, and your category mapping table. Then run one small market end-to-end before scaling to your full list.
Next step
Clone the Yellow Pages directory scraper, load your target geography list, and score one real market today. If you want a second source for the same territories, pair it with the Google Maps business data scraper. More collection tools across categories live on the data-scrape profile.
The analysis script above is yours to adapt — the metrics, thresholds, and category maps should match the markets you actually sell into, not the example ones.
Top comments (0)