Contents
Leads Dashboard is a FastAPI, React and PostgreSQL app for local-business lead generation. It collects businesses from Google Maps and the Dubai Business Directory, then has steps for finding contact emails, drafting outreach with an LLM, and sending or scheduling it. Long-running steps run as jobs, each with its own log.
This post is about one of those steps: the email finder. Given a business website, it opens a few pages in headless Chromium and returns the addresses it finds. That sounds like a regex in a loop. Most of the real work is in keeping the crawl small and keeping junk out of the results.
A small budget per site
The crawler drives Playwright's Chromium instead of fetching raw HTML, so pages that render their contact details with JavaScript still work. A real browser is expensive, so every crawl runs under four limits. The defaults live in config.py, and the batch job that finds emails for selected leads tightens them:
| Setting | Default in config.py | Find-emails job |
|---|---|---|
| Max depth | 1 | 1 |
| Page timeout | 8,000 ms | 15,000 ms |
| Concurrent pages | 5 | 2 |
| Max pages per site | 15 | 5 |
Depth 1 means the homepage plus the pages it links to.
Before any browser starts, the URL is normalized (https:// added if missing, fragment dropped) and checked against a configurable list of social domains such as facebook.com, instagram.com and linkedin.com. A lead whose website field points at a social profile is rejected with an error instead of crawled.
Breadth-first, one level at a time
The crawl is a breadth-first search over (url, depth) pairs. Each pass of the loop pulls every URL at the current depth, up to the remaining budget, into a batch:
queue = [(start_url, 0)]
while queue and len(self.crawled_urls) < self.max_pages:
current_level = []
next_queue = []
current_depth = queue[0][1] if queue else 0
for url, depth in queue:
if (
depth == current_depth
and len(self.crawled_urls) + len(current_level) < self.max_pages
):
async with self._lock:
if url not in self.crawled_urls and url not in self.failed_urls:
current_level.append((url, depth))
self.crawled_urls.add(url) # Mark immediately to avoid duplicates
else:
next_queue.append((url, depth))Two details matter. A URL goes into crawled_urls the moment it is scheduled, not when it finishes, so a link that appears on several pages is loaded once. And the budget is checked while the batch is being built, so the crawler never schedules a page it has no budget for.
The batch then runs through asyncio.gather(*tasks, return_exceptions=True), so one broken page does not cancel its siblings. Child links come from a single page.evaluate call that keeps anchors on the same hostname, strips the fragment and returns at most 50 of them.
Two limits that do different jobs
The page budget limits how much work a site gets in total. Concurrency is a separate limit, and it lives inside the per-page task:
async with self._semaphore: # Limit concurrent page loads
page = None
try:
page = await context.new_page()
page.set_default_timeout(self.page_timeout_ms)
await page.goto(
url, wait_until="domcontentloaded", timeout=self.page_timeout_ms
)
await asyncio.sleep(0.2)
emails = await self._extract_emails_from_page(page)
# ...
finally:
if page:
await page.close()gather starts a coroutine for every URL in the batch, but only as many as the semaphore allows have a tab open at once. Each page waits for domcontentloaded rather than the full load event, and the tab is closed in finally whether the page worked or timed out.
The browser context also routes every request through a handler that aborts images, media, fonts and stylesheets. The crawler only reads the DOM and its text, so there is no reason to download a hero image.
Distrusting the matches
Extraction is one page.evaluate call. It collects mailto: links (with any ?subject= part cut off), the values of data-email, data-mail and data-contact attributes, the body's innerText and the full innerHTML. Python then runs an email regex over the text and the HTML.
Running a regex over raw HTML is where the junk comes from. A retina image named logo@2x.png matches the pattern, because png looks like a top-level domain. So do noreply senders, template placeholders like yourname@yoursite.com, and addresses on Sentry and Wix domains, which the code labels service and tracking emails. Every result passes through EmailExtractor.normalize_emails, which checks it against 29 patterns like these:
DUMMY_EMAIL_PATTERNS = [
r"^(noreply|no-reply|donotreply|do-not-reply)@",
r"@godaddy\.com$", # Filter all GoDaddy emails (parking/placeholder domain)
r"^(yourname|myname|youremail|myemail|you|me|mymail)@",
r"@(example\.(com|org|net)|test\.(com|org|net)|dummy\.(com|org|net))$",
r"@sentry\.", # Any sentry subdomain
r"@(wixpress\.com|wix\.com|wikpress\.com)$",
r"@.*\.(png|jpg|jpeg|gif|svg|ico|webp|css|js)$",
]Before the patterns, it lowercases each match, drops anything shorter than six characters and removes a small hard-coded blocklist. After them, it checks length limits (64 characters for the local part, 254 overall) and returns a sorted, de-duplicated list. This is code that grows one false positive at a time; the blocklist even ends with a comment inviting more entries.
Running it as a tracked job
A batch of leads takes a while, so the endpoint does not wait:
job = await job_service.create_job(
job_type=JobType.EMAIL_FINDER,
params={"organization_ids": [str(id) for id in request.organization_ids]},
)
background_tasks.add_task(
run_find_emails_task, job.id, request.organization_ids, async_session_maker
)It creates a jobs row, hands the work to FastAPI's BackgroundTasks and returns the job ID straight away. The task opens its own database session, because the request's session is closed once the response is sent.
For each lead, the task writes an email_crawler_results row with status crawling and commits before the browser starts. Afterwards the row becomes completed with the emails, no_emails_found, or failed with the error message. Found addresses are merged into the lead's existing list through a set, and a new lead moves to enriched. Progress is written as a percentage after every lead, and the job ends as succeeded with totals for leads with and without emails.
Where it stops working
For a tool one person runs locally, this design is fine. The limits show up in three places.
The jobs live inside the API process. The cancel endpoint only flips the row to canceled; the email-finder loop never reads the status, so a canceled job keeps crawling and later marks itself succeeded. Retry creates a new job row with the same params and a retry_of_job_id link, but nothing starts it. A restart mid-batch leaves a job at running. I would move this to a small worker that claims queued jobs from the table and checks for cancellation between leads.
Each crawl also launches its own Chromium, and leads are processed one after another. That isolates sites but pays the browser start-up cost every time; one shared browser with a fresh context per site would be cheaper.
Finally, the budget check in the loop above counts every accepted URL twice: once in crawled_urls and once in current_level. The crawl still stops at max_pages, but a level gets scheduled in a few shrinking batches instead of one. It is a one-line fix, and a good argument for giving a page budget its own unit test.
Found this useful? Share it with your team.