Google Maps and Yellow Pages Scraper: How to Deduplicate Local Business Records with Python
You can merge duplicate local business records from two public directories with a short Python script: normalize phone numbers, names, and addresses; block records into candidate pairs so you are not comparing every row to every other row; score each pair; and union the pairs that clear a threshold. This article is for data analysts, RevOps teams, and developers who pull business listings from more than one source and are tired of mailing the same company twice or reporting an inflated competitor count.
The two collection tools come from the data-scrape account. The Google Maps scraper repository that documents business names, phones, addresses, ratings, review counts, and Place IDs covers the map side, and the Yellow Pages scraper that extracts business names, phones, addresses, categories, and ratings with documented JSON fields covers the directory side. Both repositories are about collecting public records. Everything below — the normalization, blocking, scoring, and merge — is the layer you add afterward, and it is the part that decides whether your merged list is trustworthy.
TL;DR
- Collect public records from each source separately and keep the original source URL on every row; provenance is what lets you audit a merge later.
- Normalize before comparing: strip phone formatting to the last ten digits, lowercase names and drop legal suffixes, and reduce street suffixes in addresses.
- Use blocking keys (phone, then a name prefix) so you only score plausible pairs — this keeps the script linear-ish instead of quadratic.
- Score with a weighted blend: name 45%, phone 35%, address 20%. Treat an exact normalized phone as a strong signal that lowers the threshold.
- Merge matched records with union-find, keep the longest name and address, average the ratings, take the largest review count, and retain every source URL.
- On a ten-record sample the script found four cross-source pairs and collapsed them into six records. Every merge is reversible because source URLs are preserved.
Why the obvious approach fails
The instinct is to compare names. If two strings look the same, they must be the same business. That breaks in predictable ways the moment you combine two real directories.
Names are not stable identifiers. One source writes "Northside Dental Care," the other writes "Northside Dental Care Inc." A strict string comparison misses the match; a loose substring comparison matches unrelated businesses that share a city or a word like "service." Neither is reliable on its own.
Phone formatting is a trap. (312) 555-0142, 312.555.0142, and 3125550142 are the same number in three shapes. Compare them raw and you will conclude the two records are different companies. Normalize them and one field becomes the strongest matching signal you have.
Addresses carry the same problem. "Randolph St" versus "Randolph Street," "Suite 4" versus "Unit 4." Address text disagrees even when the location is identical, so it works as a weak supporting signal, never as the deciding one.
Naive all-pairs comparison does not scale. Comparing every row in one file against every row in the other is O(n×m). At a few hundred rows this is fine; at fifty thousand per source it is a performance problem you created for yourself. Blocking — grouping records by a cheap shared key first — cuts the work dramatically while keeping the matches you care about.
ratings and review counts are not identity fields. Two listings with similar ratings are not the same business. Those fields are useful after a match, for describing the merged record, not for deciding the match.
What the workflow actually does
The script below treats deduplication as an entity-resolution problem with four stages. First it loads JSON from two files and attaches a source label and a stable _id to each row. Then it normalizes three fields into comparison forms. Third, it emits candidate pairs from two blocking indexes — normalized phone and the first six characters of the normalized name — so any pair appearing in either index gets scored once. Fourth, it scores the pair, unions matches with a disjoint-set structure, and writes one merged record per cluster.
The score is a weighted sum of three similarities computed with Python's standard-library difflib.SequenceMatcher: name contributes 45%, phone 35%, and address 20%. An exact normalized phone is a strong enough signal that pairs sharing one clear at 0.60 instead of the default 0.82 threshold. That two-tier rule is deliberate: it lets you merge a record where the name was entered inconsistently but the phone is identical, without loosening the threshold for pairs that only share a fuzzy name.
No network calls happen in the script. It processes files you have already collected with the two repositories. That separation matters: collection and entity resolution have different failure modes, and keeping them apart makes each one testable.
Setup and environment configuration
You need Python 3.9 or newer and no third-party packages. Export the paths to the two JSON files you collected, plus an optional output path and threshold:
export GMAPS_RECORDS_JSON="./gmaps_businesses.json"
export YP_RECORDS_JSON="./yellowpages_businesses.json"
export MERGED_OUTPUT_JSON="./merged_businesses.json"
export MATCH_THRESHOLD="0.82"
python dedupe_business_records.py
GMAPS_RECORDS_JSON and YP_RECORDS_JSON are required. The output path defaults to merged_businesses.json and the threshold to 0.82 if you leave them unset. Each input file is a JSON array of objects; the script reads the business_name/name, phone, address, city, category, rating, review_count, website, and url keys, tolerating missing values. Lower the threshold toward 0.75 if you see obvious misses in your sample, or raise it toward 0.90 if you see false merges. Tune it against labeled examples, not against a hunch.
The runnable script
import difflib
import itertools
import json
import os
import re
GOOGLE_FILE = os.environ["GMAPS_RECORDS_JSON"]
YP_FILE = os.environ["YP_RECORDS_JSON"]
OUT_FILE = os.environ.get("MERGED_OUTPUT_JSON", "merged_businesses.json")
THRESHOLD = float(os.environ.get("MATCH_THRESHOLD", "0.82"))
LEGAL_SUFFIXES = {"inc", "llc", "ltd", "co", "corp", "company", "the"}
def norm_name(value):
tokens = re.findall(r"[a-z0-9]+", (value or "").lower())
return " ".join(t for t in tokens if t not in LEGAL_SUFFIXES)
def norm_phone(value):
digits = re.sub(r"\D", "", value or "")
return digits[-10:] if len(digits) >= 10 else ""
def norm_address(value):
value = (value or "").lower()
value = re.sub(r"\b(street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|lane|ln)\b", " ", value)
return " ".join(re.findall(r"[a-z0-9]+", value))
def load(path, source):
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
return [
{
"_id": f"{source}-{i}",
"source": source,
"name": rec.get("business_name") or rec.get("name") or "",
"phone": rec.get("phone") or "",
"address": rec.get("address") or "",
"city": rec.get("city") or "",
"category": rec.get("category") or "",
"rating": rec.get("rating"),
"review_count": rec.get("review_count"),
"website": rec.get("website") or "",
"url": rec.get("url") or "https://example.com/placeholder",
}
for i, rec in enumerate(data)
]
def candidate_pairs(records):
seen = set()
key_fns = (
lambda r: ("phone", norm_phone(r["phone"])) if norm_phone(r["phone"]) else None,
lambda r: ("name", norm_name(r["name"])[:6]) if norm_name(r["name"]) else None,
)
for key_fn in key_fns:
buckets = {}
for rec in records:
key = key_fn(rec)
if key:
buckets.setdefault(key, []).append(rec)
for bucket in buckets.values():
for a, b in itertools.combinations(bucket, 2):
pair_id = tuple(sorted((a["_id"], b["_id"])))
if pair_id in seen:
continue
seen.add(pair_id)
if a["source"] != b["source"]:
yield a, b
def similarity(a, b):
name_sim = difflib.SequenceMatcher(None, norm_name(a["name"]), norm_name(b["name"])).ratio()
p1, p2 = norm_phone(a["phone"]), norm_phone(b["phone"])
phone_sim = 1.0 if p1 and p1 == p2 else 0.0
addr_sim = difflib.SequenceMatcher(None, norm_address(a["address"]), norm_address(b["address"])).ratio()
return 0.45 * name_sim + 0.35 * phone_sim + 0.20 * addr_sim
def is_match(a, b):
p1, p2 = norm_phone(a["phone"]), norm_phone(b["phone"])
if p1 and p2 and p1 == p2:
return similarity(a, b) >= 0.60
return similarity(a, b) >= THRESHOLD
def merge(group):
best_name = max(group, key=lambda r: len(r["name"]))["name"]
phones = [r["phone"] for r in group if norm_phone(r["phone"])]
sites = [r["website"] for r in group if r["website"]]
ratings = [r["rating"] for r in group if isinstance(r["rating"], (int, float))]
reviews = [r["review_count"] for r in group if isinstance(r["review_count"], (int, float))]
return {
"name": best_name,
"phone": phones[0] if phones else "",
"website": sites[0] if sites else "",
"address": max(group, key=lambda r: len(r["address"]))["address"],
"city": next((r["city"] for r in group if r["city"]), ""),
"category": next((r["category"] for r in group if r["category"]), ""),
"rating": round(sum(ratings) / len(ratings), 2) if ratings else None,
"review_count": int(max(reviews)) if reviews else None,
"sources": sorted({r["source"] for r in group}),
"source_urls": [r["url"] for r in group if r["url"]],
}
def main():
records = load(GOOGLE_FILE, "google_maps") + load(YP_FILE, "yellow_pages")
parent = {r["_id"]: r["_id"] for r in records}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[rb] = ra
matched_pairs = 0
for a, b in candidate_pairs(records):
if is_match(a, b):
union(a["_id"], b["_id"])
matched_pairs += 1
clusters = {}
for rec in records:
clusters.setdefault(find(rec["_id"]), []).append(rec)
merged = sorted((merge(g) for g in clusters.values()), key=lambda m: m["name"])
with open(OUT_FILE, "w", encoding="utf-8") as fh:
json.dump(merged, fh, indent=2, ensure_ascii=False)
print(f"input_records={len(records)} matched_cross_source_pairs={matched_pairs} merged_records={len(merged)}")
for m in merged:
print(f"- {m['name']} | {m['phone'] or 'no-phone'} | sources={','.join(m['sources'])} | rating={m['rating']}")
if __name__ == "__main__":
main()
Representative output
Running the script against a ten-record sample — five map records and five directory records, four of which are duplicates across sources — produced this console output:
input_records=10 matched_cross_source_pairs=4 merged_records=6
- Harbor Point Plumbing LLC | (312) 555-0188 | sources=google_maps,yellow_pages | rating=4.55
- Lakeview Heating and Cooling | (773) 555-0109 | sources=google_maps,yellow_pages | rating=4.25
- Northside Dental Care Inc | (312) 555-0142 | sources=google_maps,yellow_pages | rating=4.75
- Oak Street Electric Co | (773) 555-0193 | sources=google_maps,yellow_pages | rating=4.65
- Riverbend Legal Group | (312) 555-0177 | sources=google_maps | rating=4.5
- West Loop Auto Repair | (312) 555-0166 | sources=yellow_pages | rating=4.1
Four pairs merged correctly even though the names and phones were formatted differently in each source. The two single-source businesses stayed single. One merged record is worth inspecting:
{
"name": "Harbor Point Plumbing LLC",
"phone": "(312) 555-0188",
"website": "https://harborpointplumbing.example.com",
"address": "412 W Randolph Street, Chicago, IL 60606",
"city": "Chicago",
"category": "Plumber",
"rating": 4.55,
"review_count": 87,
"sources": ["google_maps", "yellow_pages"],
"source_urls": [
"https://www.google.com/maps/place/?q=place_id:gmaps-1",
"https://www.yellowpages.com/chicago-il/mip/harbor-point-plumbing-yp-1"
]
}
Note the sources array and the two source_urls. The merged rating is the mean of the two source ratings (4.6 and 4.5), and the review count keeps the larger value. Those are arbitrary but explicit policies — you can change them without touching the matching logic, which is the whole point of separating merge from score.
Build, buy, or API: a quick comparison
| Option | Setup | Maintenance | Best for | What to verify |
|---|---|---|---|---|
| This Python script | Standard library only; two JSON inputs | You tune the threshold and normalization as sources change | Small to medium lists, full control, auditable merges | Accuracy against labeled pairs before trusting output |
| Two open-source scrapers + this script | Clone the two repositories, collect, then dedupe | Collection plus matching both need care | Teams that want ownership of the whole pipeline | Each repository's current README and target-site terms |
| Managed web data API | Vendor handles collection and normalization | Vendor-managed, less local code | Production workloads where maintenance cost dominates | Current pricing, quotas, and coverage on the provider's official page |
For a deeper background on preparing local business records for research, the Chinese-language guide to web data for market research covers how collection and downstream analysis fit together. It is a public reference, not an API specification or official product documentation.
Where this is useful
- Outreach list cleanup. Before a campaign, merge the same business appearing in two directories so you do not send two emails to one company.
- Competitor counting. Report how many real competitors operate in a city, not how many rows you collected across sources.
- Directory enrichment. Fill a missing website or phone in one record using its matched twin from the other source, while keeping both source URLs.
- Market sizing. Build a de-duplicated business base for a territory before estimating density or share.
- Data quality auditing. Because every merged record lists its sources, you can measure how often your sources disagree on rating or category.
Pre-flight checklist
- [ ] Both input files are JSON arrays and every row retains a source URL.
- [ ]
GMAPS_RECORDS_JSONandYP_RECORDS_JSONpoint to the files you intend to process. - [ ] You ran the script on a small labeled sample and inspected the merges it made.
- [ ] You tested at least one false merge and one missed match before choosing
MATCH_THRESHOLD. - [ ] You understand that the phone shortcut uses the last ten digits and will behave differently for non-US numbers.
- [ ] You reviewed the target sites' terms and your applicable data-handling obligations before collecting.
Limits, compliance, and maintenance
This is a heuristic matcher, not a truth machine. It will miss records where both the name and phone differ, and it may merge two genuinely different locations that share a phone number — a franchise or a shared front desk, for example. Blocking by phone and name prefix also means a pair with neither signal in common will never be scored; add more blocking keys if that matters for your data. Review a sample of merges by hand before using the output for anything consequential.
Phone normalization here assumes ten-digit North American numbers by taking the last ten digits. Adapt norm_phone for your region, and never use it to infer anything about a person — these are business contact details from public listings.
Treat the repositories as collection examples, not as permission to collect anything. Review each target site's terms, robots directives where relevant, applicable law, and privacy requirements. Use public business data for legitimate research and automation. Do not use this workflow to access private data, bypass access controls, evade CAPTCHAs, or assemble profiles of individuals. Keep the source_urls on every record so a merge can be traced back to the page it came from, and re-check normalization rules when a source changes how it formats names or addresses.
FAQ
Is there an official API that does this deduplication?
The two repositories above are collection examples; the matching script here is local code you run yourself. Some managed data providers offer entity resolution as part of their platform. Check a provider's current documentation for what it actually includes before assuming it covers your case.
What fields do the two repositories provide?
The Google Maps repository documents names, phones, websites, addresses, categories, ratings, review counts, reviews, Place IDs, coordinates, and opening hours. The Yellow Pages repository documents business name, phone, address, city, state, ZIP, category, rating, review count, website, hours, years in business, and source URL. Availability varies by listing, so the script tolerates missing values.
How do I choose the match threshold?
Label a few dozen pairs by hand as match or non-match, run the script at several thresholds, and pick the value that minimizes the mistakes you care about most. Start at 0.82 and adjust in small steps.
What happens when a source changes how it formats phones or addresses?
Your normalized comparison fields drift and match quality drops. Keep norm_phone, norm_name, and norm_address in one place, add a test with examples from each source, and revisit them whenever you change a collector.
Can this connect to a CRM, a queue, or an AI agent?
Yes. The output is plain JSON, so you can feed the merged records into a CRM import, a message queue, or a retrieval pipeline. Preserve the source_urls field so downstream systems can cite the origin of each merged record.
Does combining two sources guarantee better data?
Only if you merge them deliberately. Two sources can repeat the same stale error, and a merge can hide a disagreement rather than resolve it. The value here is an auditable merge with explicit policies, not a claim that the result is correct.
Next step
Clone the Google Maps scraper and the Yellow Pages scraper from the data-scrape account, collect a small sample from each, and run the script above on your own two files. Compare ten merges by hand before you scale it up. That single afternoon of checking will tell you more about your data than any threshold tuning.
Top comments (0)