# US & Canada Local Business & License Scraper (OSM/FDIC) (`vesper_studio/local-directory-harvester`) Actor

Multi-source US & Canada local B2B business scraper combining OpenStreetMap (Overpass + Photon), official licensing registries (TX TDLR, FDIC, provincial), and concurrent website contact enrichment (JSON-LD, Cloudflare email decoding, MX validation, E.164 phones) in 512 MB RAM.

- **URL**: https://apify.com/vesper_studio/local-directory-harvester.md
- **Developed by:** [Xavier Richard](https://apify.com/vesper_studio) (community)
- **Categories:** Lead generation, Business, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$4.00 / 1,000 normalized local business listings

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Local Business Directory & Licensing Harvester (US & Canada)

Discover, verify, deduplicate, and contact-enrich local B2B contractors and businesses across the **United States and Canada** by combining **official government licensing registries**, **OpenStreetMap (Overpass + Komoot Photon instant fallback)**, **industry directory pages**, and **concurrent website contact extraction** — all inside a lean **512 MB RAM** HTTP-first engine with zero external sub-actor dependencies.

***

### Why Use Local Directory Harvester?

- **Zero-Key Free Sources First (512 MB RAM, 15–28s Runs)**: Runs natively over HTTP (`got-scraping` + `cheerio`) with **no paid API key required** out of the box. Free official sources run in parallel before optional paid APIs.
- **Resilient OpenStreetMap Discovery**: Automatically falls back from public Overpass mirrors to **Komoot Photon** geocoding & POI search whenever Overpass returns 502/504, delivering street addresses, postal codes, and lat/lng coordinates reliably on cloud IPs.
- **Official US & Canadian Licensing Registries**:
  - **Texas TDLR** (`data.texas.gov` Socrata Open Data — licensed electrical contractors with street address, ZIP, and telephone)
  - **FDIC BankFind API** (US bank branches & safe-deposit providers)
  - **Canadian Provincial Contractor Directories** (Nova Scotia / Atlantic & Ontario HVAC / oil tank / heat pump programs)
- **Concurrent Website Contact Enrichment**: Crawls discovered company websites concurrently (`concurrency=6`) with JSON-LD `@graph` parsing, `mailto:` extraction, **Cloudflare `data-cfemail` de-obfuscation**, E.164 phone normalization, and **DNS MX-verified B2B role emails** (`info@`, `contact@`, `sales@`, `service@`).
- **Strict Spend Guard (`maxUsd`) & `dryRun` Planner**: Tracks compute, proxy, and optional API spend continuously and stops cleanly at `budget_exhausted` before exceeding your cap.
- **Explainable Multi-Key Deduplication**: Non-destructive merge across `placeId` → E.164 phone → root domain (excluding shared platforms) → normalized name + city.
- **Google Maps-Compatible Output Schema**: Ready to import directly into CRMs, directory platforms, spreadsheets (CSV/XLSX), Clay, n8n, or Make.

***

### Built-in Vertical Profiles & Custom JSON Support

Choose a pre-configured vertical profile or supply your own `customProfile` JSON for any local service niche:

| Profile (`profile`) | Scope | Default Sources | Target Businesses |
| :--- | :---: | :--- | :--- |
| **`critical-power`** | US & CA | TX TDLR, OSM/Photon, Industry Directories, Website Enricher | Electrical contractors, IR thermography (NFPA 70B), load bank testing, generator service, arc flash studies |
| **`safe-deposit`** | US | FDIC BankFind, OSM/Photon, Website Enricher | Private vault facilities, bank branches & credit unions offering safe deposit boxes |
| **`oil-tank`** | CA | Provincial Programs, OSM/Photon, Website Enricher | Residential oil tank removal/replacement, burner/furnace maintenance, heat pump installers |
| **`custom`** | US / CA / ALL | Any combination of free & optional BYOK sources | Supply custom keywords, categories, and relevance scoring rules via `customProfile` |

***

### Input Example

```json
{
  "profile": "critical-power",
  "sources": ["osm_overpass", "registry", "directory_pages", "website_enrichment"],
  "locations": ["Houston, TX", "Austin, TX"],
  "country": "US",
  "maxPerQuery": 20,
  "maxRecords": 60,
  "maxUsd": 0.5,
  "dryRun": false
}
```

#### Optional Paid API Extensions (BYOK)

Free discovery runs automatically without API keys. You can optionally enable:

- `google_places_api` (bring your own Google Places API New key)
- `brightdata_collect_by_url` (bring your own Bright Data Datasets token)

***

### Output Dataset Schema

Every record is normalized into a flat Google Maps-compatible structure with full provenance and enrichment metadata in `_meta`:

```json
{
  "title": "LONE STAR ELECTRICAL SERVICES LLC",
  "placeId": null,
  "cid": null,
  "url": "https://lonestarelectrical.example",
  "categoryName": "Electrical Contractor",
  "categories": ["Electrical Contractor"],
  "address": "4820 WESTPARK DR, HOUSTON, TX 77027",
  "street": "4820 WESTPARK DR",
  "city": "HOUSTON",
  "state": "TX",
  "postalCode": "77027",
  "countryCode": "US",
  "phone": "(713) 555-0148",
  "phoneUnformatted": "+17135550148",
  "website": "https://lonestarelectrical.example",
  "location": { "lat": 29.7265, "lng": -95.4618 },
  "permanentlyClosed": false,
  "searchString": "critical-power | Houston, TX",
  "_meta": {
    "sources": ["registry", "website_enrichment"],
    "roleEmails": ["service@lonestarelectrical.example"],
    "mxValid": true,
    "relevanceScore": 85
  }
}
```

Key-Value Store artifacts (`OUTPUT`, `SUMMARY_CSV`, and `UNREADABLE_SITES`) are automatically generated on each run.

***

### Compliance & Polite Crawling

- **CAN-SPAM / CASL / PIPEDA B2B-first**: Extracts published business role emails (`info@`, `contact@`, `sales@`, `service@`) with MX verification and excludes personal named emails by default (`includePersonalEmails: false`).
- **OpenStreetMap Attribution (ODbL)**: Data sourced via Overpass/Photon includes `© OpenStreetMap contributors` attribution metadata.
- **Respects `robots.txt`**: Enforces per-domain rate limits and logs disallowed/blocked domains cleanly without anti-bot circumvention.

***

### Pay-Per-Event Pricing

Billed transparently per normalized local business listing delivered to the default dataset (`apify-default-dataset-item`), with `maxUsd` runtime budget protection.

***

### Local Development & Tests

```bash
npm install
npm test
npm run build
```

# Actor input Schema

## `profile` (type: `string`):

Select the target vertical profile or choose 'custom' to supply customProfile.

## `customProfile` (type: `object`):

Inline profile JSON schema when profile is set to 'custom'.

## `sources` (type: `array`):

Active discovery sources. Free sources run first by default.

## `locations` (type: `array`):

List of cities or areas to search (e.g., 'Houston, TX', 'Halifax, NS', 'Las Vegas, NV').

## `region` (type: `string`):

Optional full state or province name to divide into geographical grid cells (e.g. 'Nova Scotia', 'Texas', 'Ontario').

## `cellKm` (type: `integer`):

Size of each square grid cell in kilometers when region grid division is active.

## `country` (type: `string`):

Country scope for normalisation and search filtering.

## `keywordsOverride` (type: `array`):

Optional custom keywords to override profile defaults.

## `maxPerQuery` (type: `integer`):

Maximum number of raw records to retrieve per query / source.

## `maxRecords` (type: `integer`):

Total target listings before stopping discovery.

## `maxUsd` (type: `number`):

Strict spending limit in USD for paid APIs, proxy and compute.

## `dryRun` (type: `boolean`):

When true, plans queries, estimates costs and outputs execution plan without paid API calls.

## `costs` (type: `object`):

Unit pricing overrides for budget tracking (Google Places, Bright Data, compute, proxy).

## `googleMapsApiKey` (type: `string`):

API Key for Google Places (New) Text Search. Kept secret.

## `brightdataApiToken` (type: `string`):

API Token for Bright Data Datasets v3 API.

## `proxyConfiguration` (type: `object`):

Proxy group configuration for HTTP crawling.

## `includeGoogleRatings` (type: `boolean`):

Include totalScore and reviewsCount only when explicitly requested and not forbidden by profile.

## `includePersonalEmails` (type: `boolean`):

Include first.last@ emails instead of restricting strictly to generic role emails (info@, sales@).

## `useBrowserFallback` (type: `boolean`):

Spawn Playwright browser for JS-rendered websites (higher memory & CPU cost).

## `maxExtraPages` (type: `integer`):

Maximum number of internal pages to crawl per website for evidence and contacts.

## `blockedDomains` (type: `array`):

List of domains to avoid reading (Google Web Risk, spam directories, etc.).

## `knownIds` (type: `array`):

List of placeId, cid or license numbers already harvested to avoid recollecting.

## `since` (type: `string`):

Only harvest registry records modified or issued since this date (YYYY-MM-DD).

## Actor input object example

```json
{
  "profile": "critical-power",
  "sources": [
    "osm_overpass",
    "registry",
    "directory_pages",
    "website_enrichment"
  ],
  "locations": [
    "Houston, TX"
  ],
  "cellKm": 25,
  "country": "US",
  "maxPerQuery": 20,
  "maxRecords": 100,
  "maxUsd": 0.5,
  "dryRun": false,
  "proxyConfiguration": {
    "useApifyProxy": true
  },
  "includeGoogleRatings": false,
  "includePersonalEmails": false,
  "useBrowserFallback": false,
  "maxExtraPages": 4
}
```

# Actor output Schema

## `listings` (type: `string`):

Deduplicated local business records normalized to a Google Maps-compatible schema with street address, coordinates, E.164 phone, website, MX-verified role emails, and source provenance.

## `summary` (type: `string`):

Execution summary, per-source discovery counts, deduplication metrics, and USD budget ledger.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "locations": [
        "Houston, TX"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("vesper_studio/local-directory-harvester").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "locations": ["Houston, TX"] }

# Run the Actor and wait for it to finish
run = client.actor("vesper_studio/local-directory-harvester").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "locations": [
    "Houston, TX"
  ]
}' |
apify call vesper_studio/local-directory-harvester --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,vesper_studio/local-directory-harvester"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/3odZfCnnfiRX8Gfy6/builds/FjJpYxTKd1NLvf6rD/openapi.json
