Skip to content

Free, open-source Google Maps scraper for lead generation (Python, no API key, no Docker). Exports name, phone, email, website, rating and Instagram/Facebook/LinkedIn/TikTok/YouTube/X links to CSV. 100 places with emails in 44 s; --grid beats Google's 120 cap. MX email check, ad-pixel detection. Skill for Claude Code, Codex and Cursor.

feat: add optional Playwright fallback for website emails and social links

Mahan Jafaric514a3996448
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 8ea481c..70397bd 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -32,6 +32,7 @@ jobs:
python-version: ${{ matrix.python }}
- run: python scripts/test_scrape.py
- run: python engine/test_cdp.py
+ - run: python engine/test_website_browser.py
- run: python engine/test_engine.py
- run: bash -n scripts/scrape.sh
- run: bash scripts/test_update.sh
diff --git a/CREDITS.md b/CREDITS.md
index af14e2c..17d6bfb 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -72,3 +72,10 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+
+## Optional website rendering: Playwright
+
+The optional website enrichment fallback uses [Microsoft Playwright for Python](https://github.com/microsoft/playwright-python),
+licensed under [Apache License 2.0](https://github.com/microsoft/playwright-python/blob/main/LICENSE).
+It is installed separately through `requirements-browser.txt`; this repository does not vendor its code
+or browser binaries. The default HTTP crawl and Maps engine do not require Playwright.
diff --git a/README.md b/README.md
index 7316f6a..4b47aec 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,8 @@ drive it for you in plain English.
## Quick start
Requires Python 3.9 or newer and Google Chrome (or Chromium, Edge or Brave). The engine and the
-scripts use the Python standard library only, so there is nothing to `pip install`. No browser
+scripts use the Python standard library by default. Optional website rendering adds Playwright
+([setup](SETUP.md#optional-website-rendering-playwright)); the basic crawl needs no pip install. No browser
installed? The first start downloads Chrome for Testing once, about 100 MB, checked against a pinned
SHA-256.
@@ -94,6 +95,11 @@ Illustrative rows. The file also has six social columns after these eight (see b
`review_count` works in headless mode; see [Honest limits](#honest-limits).
+`--browser-sites` enables optional Playwright retries when HTTP finds no emails or social profile
+links. It renders JavaScript and shares the rendered homepage between both passes. Output adds
+`website_fetch_status`: `http`, `rendered`, `blocked`, `timeout` or `error`.
+See [optional setup](SETUP.md#optional-website-rendering-playwright).
+
The social columns `instagram`, `facebook`, `linkedin`, `tiktok`, `youtube` and `x` come after the eight
lead fields by default. `--no-socials` drops them. `--tech` adds
`fb_pixel`, `google_ads_tag`, `analytics`, `bing_ads`, `linkedin_insight`, `tiktok_pixel`, `cms`,
diff --git a/SETUP.md b/SETUP.md
index 3431c55..dcf6008 100644
--- a/SETUP.md
+++ b/SETUP.md
@@ -12,7 +12,7 @@ Install these once:
| Tool | Why | Get it |
|---|---|---|
-| **Python 3.9 or newer** | runs the engine and the scripts (standard library only, no `pip install`) | https://www.python.org/downloads |
+| **Python 3.9 or newer** | runs the engine and scripts; optional website rendering adds Playwright | https://www.python.org/downloads |
| **Google Chrome** *(or Chromium, Edge or Brave)* | the engine drives it, headless | https://www.google.com/chrome |
| **Docker Desktop** *(optional)* | runs the engine in a container instead, with its own Chromium | https://www.docker.com/products/docker-desktop |
| **Claude Code** *(optional but recommended)* | lets Claude drive the scraper for you | https://claude.com/claude-code |
@@ -206,6 +206,41 @@ starts.
---
+### Optional website rendering (Playwright)
+
+The standard HTTP email/social crawl needs no pip dependencies. For websites that need JavaScript,
+or return no useful email/social links over HTTP, install the optional renderer in a virtual
+environment. It uses the Chrome/Chromium already installed for the kit, with no additional browser
+download.
+
+```bash
+python3 -m venv .engine/playwright-venv
+source .engine/playwright-venv/bin/activate
+python -m pip install -r requirements-browser.txt
+python scripts/scrape.py "coffee shops in Austin TX" --depth 1 --browser-sites
+```
+
+On Windows, use `py -m venv .engine/playwright-venv`, activate with
+`.engine\playwright-venv\Scripts\Activate.ps1`, then use `python` for the remaining commands.
+
+- CLI: `--browser-sites` retries pages where the requested emails or social links were not found.
+ Email extraction also tries rendered contact/about pages when needed. Social profiles are links
+ found on business websites; social networks themselves are not crawled.
+- API: use `"browser_sites": true` with `email` and/or `socials`. Start the engine using the same
+ virtual environment's Python so it can import Playwright. The API website pass reads homepages.
+- Web UI: select **Render websites (Playwright)**. Missing optional dependencies are reported before
+ a job starts. The stock Docker image does not install this optional package.
+- HTTP results are retained. At most two browser retries run concurrently, with a 20-second budget
+ per page. Browsers use fresh contexts, block image/media/font downloads, and close after use.
+- `website_fetch_status` records `http`, `rendered`, `blocked`, `timeout` or `error`. A rendered page
+ may contain no published contact information. Authentication, CAPTCHA and access denials can
+ remain unavailable; the renderer does not solve them.
+
+Checks: `python engine/test_website_browser.py` runs offline. With Playwright installed,
+`GMSKIT_BROWSER_LIVE=1 python engine/test_website_browser.py` also renders a local JavaScript fixture
+and checks blocked/private redirects. Reference: https://playwright.dev/python/docs/library .
+
+
## 4. Run it from Claude Code or another agent
The kit ships a Claude Code skill that teaches the agent to run `scripts/scrape.py` for every scrape,
diff --git a/docs/google-maps-scraper-python.md b/docs/google-maps-scraper-python.md
index 0e15cc6..563ef4c 100644
--- a/docs/google-maps-scraper-python.md
+++ b/docs/google-maps-scraper-python.md
@@ -1,7 +1,7 @@
# Google Maps scraper in Python: the kit's dependency-free CLI
-`scripts/scrape.py` is a free Google Maps scraper Python CLI that turns a keyword and a place into a lead CSV, using only the standard library.
-It drives the kit's own engine running on your machine, so there is no API key, no pip install and no data leaving your machine.
+`scripts/scrape.py` is a free Google Maps scraper Python CLI that turns a keyword and a place into a lead CSV, using the standard library by default.
+It drives the kit's own engine running on your machine, so no Maps API key is needed. The default crawl needs no pip install; optional website rendering uses Playwright.
## Run it
@@ -33,6 +33,7 @@ On Windows, run the same commands with `py` in place of `python3`. The engine ne
| `--full` | Keeps all raw columns (the 36 classic ones plus `categories`) instead of the 8 lead fields. Review counts and weekly opening hours work headless ([SETUP §3](../SETUP.md#review-counts-hours-and-reviews)). Review texts come only with `--reviews`. |
| `--reviews N` | Adds up to N reviews per place (1-5, no reviewer names) and its star histogram (`user_reviews`, `reviews_per_rating`), one more page load per place, about 2-4 s. Raise `--max-time` for many places. |
| `--fields` | Comma-separated columns to keep, overriding the lead fields. |
+| `--browser-sites` | Optional Playwright retry for emails and social links when HTTP finds none. Adds `website_fetch_status`; requires [optional setup](../SETUP.md#optional-website-rendering-playwright). |
| `--no-socials` | Skips the social columns. By default the CSV has `instagram`, `facebook`, `linkedin`, `tiktok`, `youtube` and `x` after the lead fields, found on each website. Reuses the homepage the email crawl fetched. Zero AI tokens. `--socials` is still accepted for old commands but no longer needed. |
| `--tech` | Adds `fb_pixel`, `google_ads_tag`, `analytics`, `bing_ads`, `linkedin_insight`, `tiktok_pixel` (yes/no, blank if the site did not load), `cms`, `mobile_friendly` and a 0-100 `intent_score`, and sorts by that score. Shares the homepage fetch with the social profiles. Zero AI tokens. |
| `--keyword` | Adds an extra keyword to the same job. Repeatable. |
diff --git a/engine/jobs.py b/engine/jobs.py
index a47f0b2..cc4e7fa 100644
--- a/engine/jobs.py
+++ b/engine/jobs.py
@@ -134,8 +134,15 @@ def validate(body):
"max_time": _int(body, "max_time", 600, 1, 86400, "max time"),
"fast_mode": _bool(body, "fast_mode"), "email": _bool(body, "email"),
"verify_emails": _bool(body, "verify_emails"), "socials": _bool(body, "socials"),
+ "browser_sites": _bool(body, "browser_sites"),
"reviews_max": _int(body, "reviews_max", 0, 0, REVIEWS_MAX, "reviews_max"),
"proxies": _proxies(body.get("proxies"))}
+ if data["browser_sites"]:
+ from website_browser import check_available
+ try:
+ check_available()
+ except RuntimeError as e:
+ raise ValueError(str(e)) from e
return name.strip(), data
@@ -198,7 +205,7 @@ def locale(d):
# ── Rows ──
def fields(d):
"""A job's CSV columns: the old engine's 36, ours, then those its website pass fills."""
- return COLUMNS + EXTRA + (SOCIALS if d.get("socials") else []) + (["email_host"] if d.get("verify_emails") else [])
+ return COLUMNS + EXTRA + (SOCIALS if d.get("socials") else []) + (["email_host"] if d.get("verify_emails") else []) + (["website_fetch_status"] if d.get("browser_sites") else [])
def to_row(place, keyword):
@@ -755,7 +762,8 @@ class Worker(threading.Thread):
self._browser = None
if stage == "websites" and (d["email"] or d.get("socials")) and rows and not stop.is_set():
n, unchecked = add_site_data(rows, max(deadline - time.monotonic(), EMAIL_MIN_SECONDS), email=d["email"],
- socials=d.get("socials"), verify=d.get("verify_emails"), stop=stop.is_set)
+ socials=d.get("socials"), verify=d.get("verify_emails"), stop=stop.is_set,
+ browser_sites=d.get("browser_sites", False))
self.log(f"job {jid}: website data for {n}/{sum(1 for r in rows if r['website'])} websites")
if unchecked and not stop.is_set():
notes.append(f"{unchecked} website(s) not checked: ran out of time")
@@ -1124,7 +1132,7 @@ def find_emails(text, site=""):
return sorted(found, key=lambda e: not own(e))[:3]
-def add_site_data(rows, seconds, email=True, socials=False, verify=False, get=None, stop=lambda: False):
+def add_site_data(rows, seconds, email=True, socials=False, verify=False, get=None, stop=lambda: False, browser_sites=False):
"""One homepage fetch per row with a website, SITE_WORKERS at a time, for at most `seconds` or
until stop() is true: `emails` (joined by ", ", like the old engine), the social columns, and
with verify an MX check of each address's domain (dns.google) that drops domains that do not
@@ -1133,6 +1141,15 @@ def add_site_data(rows, seconds, email=True, socials=False, verify=False, get=No
def work(r):
page, out = get(r["website"]), {}
+ if browser_sites:
+ out["website_fetch_status"] = "http" if page else "error"
+ missing_email = email and not r.get("emails") and not find_emails(page, site_host(r["website"]))
+ missing_socials = socials and not any(find_socials(page).values())
+ if missing_email or missing_socials:
+ from website_browser import render
+ rendered = render(r["website"], _public_ip)
+ out["website_fetch_status"] = rendered["status"]
+ page += "\n" + rendered["html"]
if email and not r.get("emails"):
found = find_emails(page, site_host(r["website"]))
if verify:
@@ -1157,5 +1174,5 @@ def add_site_data(rows, seconds, email=True, socials=False, verify=False, get=No
if not f.exception():
got = {k: v for k, v in f.result().items() if v}
futs[f].update(got)
- n += bool(got)
+ n += any(k != "website_fetch_status" for k in got)
return n, len(pending)
diff --git a/engine/serve.py b/engine/serve.py
index 3a337a4..aa1a0b1 100644
--- a/engine/serve.py
+++ b/engine/serve.py
@@ -28,7 +28,7 @@ for _stream in (sys.stdout, sys.stderr): # ✓ and accented names on a Windows
except (AttributeError, ValueError):
pass
-VERSION = "2.0.0"
+VERSION = "2.0.1-dev.1"
MARK = f"gmskit-engine/{VERSION}" # X-Engine header: tells scripts/engine.py this engine from others
REPO = "https://github.com/Mahanaicoach/google-maps-scraper-kit"
# The web UI's sponsor box: the browser reads this static file from GitHub (cached a day, no
@@ -173,6 +173,7 @@ JOB_PROPS = {
"email": {"type": "boolean", "description": "visit each website's homepage for emails"},
"verify_emails": {"type": "boolean", "description": "with email: check each address's domain over DNS (dns.google), "
"drop domains that do not exist, add email_host"},
+ "browser_sites": {"type": "boolean", "description": "optional Playwright retry when HTTP finds no email or social links; adds website_fetch_status"},
"socials": {"type": "boolean", "description": "visit each website's homepage for Instagram, Facebook, LinkedIn, "
"TikTok, YouTube and X links"},
"reviews_max": {"type": "integer", "description": "0-5 reviews per place from its panel, one page load per place (headless supported)"},
@@ -390,6 +391,7 @@ progress {{ display: block; width: 100%; max-width: 200px; height: 6px; margin-t
<fieldset class="collect"><legend>Collect</legend>
<label class="chip"><input type="checkbox" id="email" checked> Emails</label>
<label class="chip"><input type="checkbox" id="socials" checked> Social profiles</label>
+ <label class="chip"><input type="checkbox" id="browser-sites"> Render websites (Playwright)</label>
</fieldset>
<details><summary>Location and language</summary><div class="body">
<p class="wide soft">Each job centres the map on its city.</p>
@@ -572,7 +574,7 @@ $('f').addEventListener('submit', async ev => {{
const body = {{name: Array.from(keywords[0] + (keywords.length > 1 ? ' +' + (keywords.length - 1) + ' more' : '')).slice(0, 200).join(''),
keywords, lang: $('lang').value.trim().toLowerCase(), country: $('country').value.trim().toLowerCase() || c.country.toLowerCase(),
lat: c.lat, lon: c.lon, zoom: +$('zoom').value || 15, depth: +$('depth').value, max_time: +$('max_time').value,
- email: $('email').checked, socials: $('socials').checked, verify_emails: $('verify').checked,
+ email: $('email').checked, socials: $('socials').checked, browser_sites: $('browser-sites').checked, verify_emails: $('verify').checked,
reviews_max: +$('reviews').value || 0}};
if (proxies.length) body.proxies = proxies;
const r = await api('POST', '/api/v1/jobs', body), d = await r.json();
diff --git a/engine/test_website_browser.py b/engine/test_website_browser.py
new file mode 100644
index 0000000..1f33132
--- /dev/null
+++ b/engine/test_website_browser.py
@@ -0,0 +1,130 @@
+"""Offline checks; GMSKIT_BROWSER_LIVE=1 also renders a local JavaScript fixture with Playwright."""
+import json
+import os
+import socket
+import sys
+import threading
+import time
+import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from unittest.mock import Mock, patch
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import jobs
+import website_browser as web
+
+
+class PublicProxy(unittest.TestCase):
+ def test_private_or_mixed_dns_never_connects(self):
+ answers = [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 443)),
+ (socket.AF_INET, socket.SOCK_STREAM, 6, '', ('127.0.0.1', 443))]
+ with patch.object(socket, 'getaddrinfo', return_value=answers), patch.object(socket, 'socket') as make:
+ with self.assertRaises(OSError):
+ web._connect_public('untrusted.test', 443, jobs._public_ip, time.monotonic() + 5)
+ make.assert_not_called()
+
+ def test_connection_uses_resolved_ip_and_checks_peer(self):
+ answers = [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 443))]
+ peer = Mock()
+ peer.getpeername.return_value = ('127.0.0.1', 443)
+ with patch.object(socket, 'getaddrinfo', return_value=answers), patch.object(socket, 'socket', return_value=peer):
+ with self.assertRaises(OSError):
+ web._connect_public('untrusted.test', 443, jobs._public_ip, time.monotonic() + 5)
+ peer.connect.assert_called_once_with(('93.184.216.34', 443))
+ peer.close.assert_called()
+
+ def test_invalid_url_is_blocked_without_starting_playwright(self):
+ for url in ('file:///etc/passwd', 'ftp://example.com', 'https://user:[email protected]', 'http://['):
+ with patch.object(web, 'check_available') as available:
+ self.assertEqual(web.render(url, jobs._public_ip)['status'], 'blocked')
+ available.assert_not_called()
+
+ def test_missing_dependency_is_actionable(self):
+ with patch.dict(sys.modules, {'playwright': None, 'playwright.sync_api': None}):
+ with self.assertRaisesRegex(RuntimeError, 'requirements-browser.txt'):
+ web.check_available()
+
+
+class WebsiteEnrichment(unittest.TestCase):
+ def test_engine_retries_empty_http_for_emails_and_socials_once(self):
+ html = '<a href="mailto:[email protected]">Email</a><a href="https://instagram.com/fixture_business">IG</a>'
+ rows = [{'website': 'https://fixture-business.test', 'emails': ''}]
+ with patch.object(web, 'render', return_value={'html': html, 'status': 'rendered'}) as render:
+ jobs.add_site_data(rows, 5, socials=True, browser_sites=True, get=lambda _: '')
+ self.assertEqual(rows[0]['emails'], '[email protected]')
+ self.assertEqual(rows[0]['instagram'], 'https://instagram.com/fixture_business')
+ self.assertEqual(rows[0]['website_fetch_status'], 'rendered')
+ render.assert_called_once()
+
+ def test_engine_keeps_fast_path_and_reports_blocks_without_fabricating_data(self):
+ rows = [{'website': 'https://fixture-business.test', 'emails': ''}]
+ with patch.object(web, 'render') as render:
+ jobs.add_site_data(rows, 5, browser_sites=True, get=lambda _: '[email protected]')
+ render.assert_not_called()
+ self.assertEqual(rows[0]['website_fetch_status'], 'http')
+ rows[0]['emails'] = ''
+ with patch.object(web, 'render', return_value={'html': '', 'status': 'blocked'}):
+ jobs.add_site_data(rows, 5, socials=True, browser_sites=True, get=lambda _: '')
+ self.assertEqual(rows[0]['emails'], '')
+ self.assertNotIn('instagram', rows[0])
+ self.assertEqual(rows[0]['website_fetch_status'], 'blocked')
+
+ def test_api_flag_is_typed_and_adds_status_column(self):
+ body = {'name': 'test', 'keywords': ['cafes'], 'lang': 'en', 'lat': '1', 'lon': '2', 'max_time': 60}
+ with self.assertRaisesRegex(ValueError, 'invalid browser_sites'):
+ jobs.validate(dict(body, browser_sites='false'))
+ with patch.object(web, 'check_available', return_value='/chrome'):
+ _, data = jobs.validate(dict(body, browser_sites=True))
+ self.assertIn('website_fetch_status', jobs.fields(data))
+
+
+class Fixture(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ if self.path == '/blocked':
+ self.send_error(403)
+ return
+ if self.path == '/redirect':
+ self.send_response(302)
+ self.send_header('Location', f'http://127.0.0.2:{self.server.server_port}/')
+ self.end_headers()
+ return
+ if self.path == '/data':
+ body = json.dumps({'mail': ['hello', 'fixture-business.test'], 'profile': 'fixture_business'}).encode()
+ else:
+ body = b'''<!doctype html><title>Local business fixture</title><main>Loading</main>
+ <script>fetch('/data').then(r=>r.json()).then(d=>{
+ document.querySelector('main').innerHTML = '<a href="mailto:'+d.mail.join('@')+'">Contact</a>'+
+ '<a href="https://instagram.com/'+d.profile+'">Instagram</a>'; });</script>'''
+ self.send_response(200)
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+
[email protected](os.environ.get('GMSKIT_BROWSER_LIVE') == '1', 'optional real-browser fixture')
+class LiveBrowser(unittest.TestCase):
+ def test_javascript_links_and_private_destinations(self):
+ with ThreadingHTTPServer(('127.0.0.1', 0), Fixture) as server:
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ url = f'http://127.0.0.1:{server.server_port}/'
+ # Only this in-process test fixture is permitted. Production uses the public-IP guard.
+ local_fixture = lambda ip: ip == '127.0.0.1'
+ result = web.render(url, local_fixture)
+ self.assertEqual(result['status'], 'rendered')
+ self.assertEqual(jobs.find_emails(result['html']), ['[email protected]'])
+ self.assertEqual(jobs.find_socials(result['html'])['instagram'], 'https://instagram.com/fixture_business')
+ self.assertEqual(web.render(url + 'blocked', local_fixture)['status'], 'blocked')
+ self.assertEqual(web.render(url + 'redirect', local_fixture)['status'], 'blocked')
+ self.assertEqual(web.render(url, jobs._public_ip)['status'], 'blocked')
+ finally:
+ server.shutdown()
+ thread.join(2)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/engine/website_browser.py b/engine/website_browser.py
new file mode 100644
index 0000000..486f4f6
--- /dev/null
+++ b/engine/website_browser.py
@@ -0,0 +1,173 @@
+"""Optional Playwright rendering for business website email and social-link enrichment.
+
+Each render owns its Playwright instance (the API is not thread-safe). At most two run at once.
+The browser's HTTP proxy pins public DNS addresses and checks connected peers, including for
+redirects, scripts and iframes. It preserves the existing website fetcher's private-network guard.
+"""
+import select
+import socket
+import threading
+import time
+import urllib.parse
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+_SLOTS = threading.BoundedSemaphore(2)
+SETUP = "Install optional rendering with: python3 -m pip install -r requirements-browser.txt"
+
+
+def check_available():
+ try:
+ from playwright.sync_api import sync_playwright # noqa: F401
+ except ImportError as e:
+ raise RuntimeError(SETUP) from e
+ from browser import find_chrome
+ path = find_chrome()
+ if not path:
+ raise RuntimeError("Website rendering needs Chrome/Chromium. Install Chrome or set CHROME to its path.")
+ return path
+
+
+def _connect_public(host, port, public_ip, deadline):
+ """Resolve once, reject mixed/private answers, and connect to a validated numeric address."""
+ infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
+ if not infos or not all(public_ip(i[4][0]) for i in infos):
+ raise OSError("non-public destination")
+ for family, kind, proto, _, address in infos:
+ peer = socket.socket(family, kind, proto)
+ try:
+ peer.settimeout(min(5, max(0.1, deadline - time.monotonic())))
+ peer.connect(address)
+ if not public_ip(peer.getpeername()[0]):
+ raise OSError("non-public peer")
+ return peer
+ except OSError:
+ peer.close()
+ raise OSError("destination unavailable")
+
+
+class _ProxyHandler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _relay(self, peer):
+ with peer:
+ while not self.server.stopped.is_set() and time.monotonic() < self.server.deadline:
+ ready, _, _ = select.select([self.connection, peer], [], [], 0.2)
+ for source in ready:
+ data = source.recv(65536)
+ if not data:
+ return
+ (peer if source is self.connection else self.connection).sendall(data)
+
+ def do_CONNECT(self):
+ try:
+ dest = urllib.parse.urlsplit("//" + self.path)
+ if not dest.hostname or dest.username or dest.password or dest.path:
+ raise ValueError("invalid destination")
+ peer = _connect_public(dest.hostname, dest.port or 443, self.server.public_ip, self.server.deadline)
+ except (OSError, ValueError, UnicodeError):
+ self.send_error(403, "Destination unavailable")
+ return
+ try:
+ self.send_response(200, "Connection established")
+ self.end_headers()
+ self._relay(peer)
+ except OSError:
+ pass
+ finally:
+ peer.close()
+
+ def do_GET(self):
+ try:
+ dest = urllib.parse.urlsplit(self.path)
+ if dest.scheme != "http" or not dest.hostname or dest.username or dest.password:
+ raise ValueError("invalid destination")
+ peer = _connect_public(dest.hostname, dest.port or 80, self.server.public_ip, self.server.deadline)
+ except (OSError, ValueError, UnicodeError):
+ self.send_error(403, "Destination unavailable")
+ return
+ try:
+ path = urllib.parse.urlunsplit(("", "", dest.path or "/", dest.query, ""))
+ lines = [f"{self.command} {path} HTTP/1.1", f"Host: {dest.netloc}", "Connection: close"]
+ lines += [f"{k}: {v}" for k, v in self.headers.items()
+ if k.lower() not in ("host", "connection", "proxy-connection", "proxy-authorization",
+ "content-length", "transfer-encoding")]
+ peer.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1"))
+ self._relay(peer)
+ except OSError:
+ peer.close()
+
+ do_HEAD = do_GET
+
+
+class _PublicProxy(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, public_ip, deadline):
+ super().__init__(("127.0.0.1", 0), _ProxyHandler)
+ self.public_ip, self.deadline, self.stopped = public_ip, deadline, threading.Event()
+
+ def __enter__(self):
+ self.thread = threading.Thread(target=self.serve_forever, daemon=True)
+ self.thread.start()
+ return f"http://127.0.0.1:{self.server_port}"
+
+ def __exit__(self, *args):
+ self.stopped.set()
+ self.shutdown()
+ self.server_close()
+ self.thread.join(2)
+
+
+def render(url, public_ip, timeout=20):
+ """{html, status}: render public content, with bounded waits and no persistent browser state."""
+ failure = lambda status: {"html": "", "status": status}
+ try:
+ parsed = urllib.parse.urlsplit(url if "://" in url else "https://" + url)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
+ return failure("blocked")
+ url = parsed.geturl()
+ except ValueError:
+ return failure("blocked")
+ deadline = time.monotonic() + timeout
+ if not _SLOTS.acquire(timeout=max(0, timeout)):
+ return failure("timeout")
+ try:
+ path = check_available()
+ from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout
+ def left():
+ return max(1, int((deadline - time.monotonic()) * 1000))
+ with _PublicProxy(public_ip, deadline) as proxy, sync_playwright() as pw:
+ with pw.chromium.launch(executable_path=path, headless=True, timeout=left(),
+ chromium_sandbox=True, proxy={"server": proxy},
+ args=["--proxy-bypass-list=<-loopback>",
+ "--force-webrtc-ip-handling-policy=disable_non_proxied_udp"]) as browser:
+ context = browser.new_context(service_workers="block", accept_downloads=False)
+ try:
+ def route_request(route):
+ req = route.request
+ if (req.resource_type in ("image", "media", "font") or req.method not in ("GET", "HEAD")
+ or urllib.parse.urlsplit(req.url).scheme not in ("http", "https")):
+ route.abort()
+ else:
+ route.continue_()
+ context.route("**/*", route_request)
+ page = context.new_page()
+ response = page.goto(url, wait_until="domcontentloaded", timeout=left())
+ if response and response.status >= 400:
+ return failure("blocked" if response.status in (401, 403, 429) else "error")
+ try:
+ page.wait_for_load_state("networkidle", timeout=min(3000, left()))
+ except PlaywrightTimeout:
+ pass # analytics may never settle; keep the rendered DOM
+ title = page.title().lower()
+ if any(t in title for t in ("just a moment", "access denied", "verify you are human", "captcha")):
+ return failure("blocked")
+ return {"html": page.content()[:400_000], "status": "rendered"}
+ finally:
+ context.close()
+ except Exception as e:
+ # No exception text: URLs, proxy credentials and page contents must not leak into logs.
+ return failure("timeout" if "timeout" in type(e).__name__.lower() else "error")
+ finally:
+ _SLOTS.release()
diff --git a/requirements-browser.txt b/requirements-browser.txt
new file mode 100644
index 0000000..2c964a4
--- /dev/null
+++ b/requirements-browser.txt
@@ -0,0 +1,2 @@
+# Optional website rendering. This release supports the kit's Python 3.9+ minimum.
+playwright==1.60.0
diff --git a/scripts/scrape.py b/scripts/scrape.py
index afdc37f..d98d52e 100755
--- a/scripts/scrape.py
+++ b/scripts/scrape.py
@@ -627,6 +627,14 @@ def _fetch_cached(url):
"""Homepage fetch shared by the email crawl, --socials and --tech (one fetch per site)."""
return _fetch_html(url, timeout=8)
[email protected]_cache(maxsize=128)
+def _render_site(url):
+ """Rendered homepages shared by email and social extraction during this CLI run."""
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "engine"))
+ from website_browser import render
+ return render(url, _is_public_ip)
+
+
def _find_socials(html):
out = {k: "" for k in SOCIAL_FIELDS}
for plat, rx in SOCIAL_RE.items():
@@ -656,13 +664,22 @@ def _each_site(todo, work, label, workers=None):
print(f"\r {label}: {done}/{len(todo)} checked", end="", flush=True)
print(f" ({failed} skipped after an error)" if failed else "")
-def enrich_sites(results, find, fields, label, workers=None):
+def enrich_sites(results, find, fields, label, workers=None, browser_sites=False):
"""Merge find(homepage html) into every lead that has a website. Zero LLM tokens."""
for r in results: # make sure every row has the keys
for k in fields:
r.setdefault(k, "")
- _each_site([r for r in results if r.get("website")],
- lambda r: r.update(find(_fetch_cached(r["website"]))), label, workers)
+ def work(r):
+ page = _fetch_cached(r["website"])
+ found = find(page)
+ if browser_sites and not any(found.values()):
+ rendered = _render_site(r["website"])
+ r["website_fetch_status"] = rendered["status"]
+ found = find(page + "\n" + rendered["html"])
+ elif browser_sites:
+ r.setdefault("website_fetch_status", "http")
+ r.update(found)
+ _each_site([r for r in results if r.get("website")], work, label, workers)
# ── Optional ad and tech signals (--tech): who already spends on marketing ──────
@@ -825,7 +842,7 @@ def contact_links(html, base_url):
out.append(url)
return out[:3]
-def enrich_emails(results, deep=True, workers=None):
+def enrich_emails(results, deep=True, workers=None, browser_sites=False):
"""Fill empty `emails` from the homepage, then (deep) up to 3 contact/about pages. Zero LLM tokens."""
def work(r):
site = r["website"]
@@ -834,6 +851,19 @@ def enrich_emails(results, deep=True, workers=None):
if deep and home and not found:
pages = "\n".join(_fetch_html(u, timeout=8) for u in contact_links(home, site))
found = extract_emails(pages, site)
+ if browser_sites and not found:
+ rendered = _render_site(site)
+ r["website_fetch_status"] = rendered["status"]
+ rendered_home = rendered["html"]
+ found = extract_emails(rendered_home, site)
+ if deep and rendered_home and not found:
+ for url in contact_links(rendered_home, site):
+ contact = _render_site(url)
+ found = extract_emails(contact["html"], site)
+ if found:
+ break
+ elif browser_sites:
+ r.setdefault("website_fetch_status", "http")
r["emails"] = ", ".join(found)
_each_site([r for r in results if r.get("website") and not r.get("emails")], work, "emails", workers)
@@ -999,6 +1029,9 @@ def main():
ap.add_argument("--no-socials", dest="socials", action="store_false", default=True,
help="skip the social profiles (Instagram, Facebook, LinkedIn, TikTok, YouTube and X links on "
"each website), which are on by default and cost 0 LLM tokens")
+ ap.add_argument("--browser-sites", action="store_true",
+ help="retry websites with Playwright when HTTP finds no emails or social links; "
+ "requires requirements-browser.txt and Chrome, adds website_fetch_status")
ap.add_argument("--socials", dest="socials", action="store_true", help=argparse.SUPPRESS) # the old opt-in
ap.add_argument("--tech", action="store_true",
help="also detect Meta Pixel, Google Ads tag, analytics, Bing, LinkedIn and TikTok "
@@ -1019,6 +1052,15 @@ def main():
help="drop places already in this earlier results file (.csv or .json); repeatable")
f.add_argument("--limit", type=int, metavar="N", help="stop at N rows after filtering")
a = ap.parse_args()
+ if a.browser_sites:
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "engine"))
+ from website_browser import check_available
+ try:
+ check_available()
+ except RuntimeError as e:
+ sys.exit(f"✗ {e}")
+ _render_site.cache_clear()
+
keywords = collect_keywords(a)
if not keywords:
@@ -1158,7 +1200,7 @@ def main():
if a.email and "emails" in fields and not a.no_website: # no website, nothing to crawl
pages = "homepage, then contact and about pages" if a.deep_emails else "homepage only"
print(f"▶ Emails: checking each business website ({pages}, {SITE_WORKERS} at a time)…")
- enrich_emails(rows, deep=a.deep_emails)
+ enrich_emails(rows, deep=a.deep_emails, browser_sites=a.browser_sites)
total, n = sum(1 for r in rows if r.get("emails")), len(rows)
print(f" emails found for {total}/{n} businesses ({round(100 * total / n) if n else 0}%)")
if a.verify_emails:
@@ -1174,11 +1216,14 @@ def main():
# Enrichment runs on the raw rows, which always carry the website, whatever --fields keeps.
if a.socials:
print("▶ Finding socials (Instagram / Facebook / LinkedIn / TikTok / YouTube / X) on each website…")
- enrich_sites(rows, _find_socials, SOCIAL_FIELDS, "socials")
+ enrich_sites(rows, _find_socials, SOCIAL_FIELDS, "socials", browser_sites=a.browser_sites)
fields = fields + SOCIAL_FIELDS
found = sum(1 for r in rows if any(r.get(k) for k in SOCIAL_FIELDS))
print(f" socials found for {found}/{len(rows)} businesses")
+ if a.browser_sites:
+ fields = fields + ["website_fetch_status"]
+
if a.tech:
print("▶ Checking ad pixels, analytics and site platform on each website (0 LLM tokens)…")
enrich_sites(rows, _find_tech, TECH_FIELDS, "tech")
diff --git a/scripts/test_scrape.py b/scripts/test_scrape.py
index d40cbab..2504191 100644
--- a/scripts/test_scrape.py
+++ b/scripts/test_scrape.py
@@ -1089,5 +1089,66 @@ class AuditGuards(unittest.TestCase):
self.assertEqual(scrape._env_value("plain # note"), "plain")
self.assertEqual(scrape._env_value("'q'"), "q")
+class BrowserSites(unittest.TestCase):
+ def test_cli_flag_keeps_rendered_results_and_status_in_csv(self):
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "engine"))
+ import website_browser
+ page = '<a href="mailto:[email protected]">Email</a><a href="https://instagram.com/fixture_business">IG</a>'
+ with tempfile.TemporaryDirectory() as tmp:
+ out = os.path.join(tmp, "leads.csv")
+ argv = ["scrape.py", "test in city", "1", "2", "--browser-sites", "--out", out]
+ with mock.patch.object(website_browser, "check_available", return_value="/chrome"), \
+ mock.patch.object(website_browser, "render", return_value={"html": page, "status": "rendered"}), \
+ mock.patch.object(scrape, "req", return_value=(200, b"null")), \
+ mock.patch.object(scrape, "run_job", return_value=("j1", [{"title": "Fixture", "website": "https://fixture-business.test", "emails": ""}])), \
+ mock.patch.object(scrape, "_fetch_cached", return_value=""), \
+ mock.patch.object(sys, "argv", argv), redirect_stdout(io.StringIO()):
+ scrape.main()
+ with open(out) as f:
+ row = next(csv.DictReader(f))
+ self.assertEqual(row["emails"], "[email protected]")
+ self.assertEqual(row["instagram"], "https://instagram.com/fixture_business")
+ self.assertEqual(row["website_fetch_status"], "rendered")
+ scrape._render_site.cache_clear()
+
+ def test_rendered_home_is_shared_by_email_and_social_extraction(self):
+ engine_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "engine")
+ sys.path.insert(0, engine_dir)
+ import website_browser
+ page = '<a href="mailto:[email protected]">Email</a><a href="https://instagram.com/fixture_business">IG</a>'
+ rows = [{"website": "https://fixture-business.test", "emails": ""}]
+ scrape._render_site.cache_clear()
+ try:
+ with mock.patch.object(scrape, "_fetch_cached", return_value=""), \
+ mock.patch.object(website_browser, "render", return_value={"html": page, "status": "rendered"}) as render, \
+ redirect_stdout(io.StringIO()):
+ scrape.enrich_emails(rows, browser_sites=True)
+ scrape.enrich_sites(rows, scrape._find_socials, scrape.SOCIAL_FIELDS, "socials", browser_sites=True)
+ self.assertEqual(rows[0]["emails"], "[email protected]")
+ self.assertEqual(rows[0]["instagram"], "https://instagram.com/fixture_business")
+ self.assertEqual(rows[0]["website_fetch_status"], "rendered")
+ render.assert_called_once()
+ finally:
+ scrape._render_site.cache_clear()
+
+ def test_rendered_contact_page_is_used_when_homepage_has_no_email(self):
+ rows = [{"website": "https://fixture-business.test", "emails": ""}]
+ def render(url):
+ content = '<a href="/contact">Contact</a>' if url.endswith('.test') else '[email protected]'
+ return {"html": content, "status": "rendered"}
+ with mock.patch.object(scrape, "_fetch_cached", return_value=""), \
+ mock.patch.object(scrape, "_render_site", side_effect=render), redirect_stdout(io.StringIO()):
+ scrape.enrich_emails(rows, browser_sites=True)
+ self.assertEqual(rows[0]["emails"], "[email protected]")
+
+ def test_http_success_never_starts_browser(self):
+ rows = [{"website": "https://fixture-business.test", "emails": ""}]
+ with mock.patch.object(scrape, "_fetch_cached", return_value="[email protected]"), \
+ mock.patch.object(scrape, "_render_site") as render, redirect_stdout(io.StringIO()):
+ scrape.enrich_emails(rows, browser_sites=True)
+ render.assert_not_called()
+ self.assertEqual(rows[0]["website_fetch_status"], "http")
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)