Contact information extraction is a common scraping task: building lead lists, verifying business data, aggregating directory information, or enriching company records. The challenge is that contact data appears in dozens of formats and layouts across the web — and HTML noise (scripts, nav, footers) makes regex matching against raw HTML unreliable.
This guide covers a three-tier approach: regex for structured patterns, UnWeb Markdown conversion for cleaner input, and LLM-assisted extraction for complex pages where patterns don’t work reliably.
Regex Patterns for Common Contact Data
Start with regex — it’s fast, cheap, and works well for clearly formatted data:
import re
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class ContactInfo:
emails: list[str] = field(default_factory=list)
phones: list[str] = field(default_factory=list)
addresses: list[str] = field(default_factory=list)
social_profiles: dict[str, str] = field(default_factory=dict)
website: Optional[str] = None
def extract_emails(text: str) -> list[str]:
pattern = re.compile(
r'\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b'
)
emails = pattern.findall(text)
# Deduplicate while preserving order
seen = set()
return [e.lower() for e in emails if not (e.lower() in seen or seen.add(e.lower()))]
def extract_phones(text: str) -> list[str]:
"""Extract US/international phone numbers in common formats."""
patterns = [
r'\+?1?\s*[-.]?\s*\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}', # US formats
r'\+\d{1,3}[\s.-]?\(?\d{1,4}\)?[\s.-]?\d{1,4}[\s.-]?\d{1,9}', # International
]
phones = []
for pattern in patterns:
phones.extend(re.findall(pattern, text))
# Normalize: remove spaces and formatting characters
normalized = [re.sub(r'[\s.\-()]', '', p) for p in phones]
# Deduplicate
seen = set()
return [p for p in normalized if not (p in seen or seen.add(p))]
def extract_social_profiles(text: str, base_url: str = "") -> dict[str, str]:
"""Extract social media profile URLs."""
platforms = {
'linkedin': r'(?:https?://)?(?:www\.)?linkedin\.com/(?:in|company)/[\w\-]+/?',
'twitter': r'(?:https?://)?(?:www\.)?(?:twitter|x)\.com/[\w]+',
'github': r'(?:https?://)?(?:www\.)?github\.com/[\w\-]+',
'facebook': r'(?:https?://)?(?:www\.)?facebook\.com/[\w.\-]+',
'instagram': r'(?:https?://)?(?:www\.)?instagram\.com/[\w.\-]+',
}
found = {}
for platform, pattern in platforms.items():
match = re.search(pattern, text, re.IGNORECASE)
if match:
url = match.group(0)
if not url.startswith('http'):
url = 'https://' + url
found[platform] = url
return found
def extract_contact_regex(text: str) -> ContactInfo:
return ContactInfo(
emails=extract_emails(text),
phones=extract_phones(text),
social_profiles=extract_social_profiles(text),
)
Why Markdown Conversion Improves Extraction Quality
Raw HTML contains a lot of noise that breaks contact extraction:
- Email addresses in JavaScript strings, href attributes, and encoded as
user [at] domain.comto avoid scrapers - Phone numbers formatted differently in visible text vs.
tel:links - Navigation footers that repeat the same contact info dozens of times
- Script tags with email-like strings that aren’t real emails
Converting to Markdown first removes most of this noise — you get the visible text content, structured as it appears on the page:
import httpx
UNWEB_API_KEY = "your_api_key"
async def fetch_as_markdown(url: str, client: httpx.AsyncClient) -> str:
response = await client.get(
"https://api.unweb.info/v1/convert",
params={"url": url},
headers={"Authorization": f"Bearer {UNWEB_API_KEY}"},
timeout=30.0,
)
response.raise_for_status()
return response.json()["markdown"]
async def extract_contacts_from_url(url: str, client: httpx.AsyncClient) -> ContactInfo:
markdown = await fetch_as_markdown(url, client)
return extract_contact_regex(markdown)
Also check the /contact page: Many sites have a dedicated contact page with more complete information. If you’re scraping a business site, fetch both the homepage and /contact or /about paths and merge the results.
LLM-Assisted Extraction for Complex Layouts
Regex works well for cleanly formatted contact data. It breaks down when:
- Names and job titles are interleaved with contact info (“John Smith, CEO, john@company.com, 415-555-0100”)
- Addresses span multiple lines with inconsistent formatting
- Multiple contacts need to be extracted as separate entities
- Contact data is embedded in sentences (“Reach us at john@example.com or call during business hours”)
For these cases, a small Claude model produces much better results:
import anthropic
import json
client_ai = anthropic.Anthropic()
def extract_contacts_llm(markdown: str, context: str = "business contact page") -> list[dict]:
"""
Use Claude to extract structured contact information from Markdown.
Returns a list of contact dicts.
"""
message = client_ai.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"""Extract all contact information from this {context}.
Return a JSON array where each object has these fields (omit fields that aren't present):
- name (string): Person or business name
- title (string): Job title or role
- email (string): Email address
- phone (string): Phone number, normalized as +1-XXX-XXX-XXXX if US
- address (string): Full postal address
- linkedin (string): LinkedIn profile URL
- twitter (string): Twitter/X profile URL
- website (string): Website URL
If multiple contacts are present, return one object per contact.
If only a business (no named person), return one object for the business.
Return [] if no contact information is found.
Content:
{markdown[:4000]}"""
}]
)
try:
raw = message.content[0].text.strip()
json_match = re.search(r'\[.*\]', raw, re.DOTALL)
if json_match:
return json.loads(json_match.group(0))
except (json.JSONDecodeError, AttributeError):
pass
return []
Handling Obfuscated Emails
Some sites obfuscate emails to prevent scraping. Common patterns and how to handle them:
def deobfuscate_email(text: str) -> list[str]:
"""Detect and convert common email obfuscation patterns."""
emails = []
# Pattern 1: "user [at] domain [dot] com"
pattern1 = re.compile(
r'[\w.+\-]+\s*\[at\]\s*[\w.\-]+\s*\[dot\]\s*[a-z]{2,}',
re.IGNORECASE
)
for match in pattern1.finditer(text):
clean = match.group(0)
clean = re.sub(r'\s*\[at\]\s*', '@', clean, flags=re.IGNORECASE)
clean = re.sub(r'\s*\[dot\]\s*', '.', clean, flags=re.IGNORECASE)
emails.append(clean.lower().strip())
# Pattern 2: "user (at) domain.com"
pattern2 = re.compile(
r'[\w.+\-]+\s*\(at\)\s*[\w.\-]+\.[a-z]{2,}',
re.IGNORECASE
)
for match in pattern2.finditer(text):
clean = re.sub(r'\s*\(at\)\s*', '@', match.group(0), flags=re.IGNORECASE)
emails.append(clean.lower().strip())
# Pattern 3: HTML entity encoding ("john@...")
# This is handled naturally when UnWeb converts the page to Markdown
return emails
Batch Extraction Across Multiple URLs
import asyncio
import csv
from dataclasses import asdict
async def extract_contacts_batch(
urls: list[str],
use_llm: bool = False,
concurrency: int = 3,
) -> list[dict]:
semaphore = asyncio.Semaphore(concurrency)
results = []
async with httpx.AsyncClient(
headers={"User-Agent": "ContactExtractor/1.0"},
follow_redirects=True,
timeout=30.0,
) as client:
async def process_url(url: str) -> dict:
async with semaphore:
try:
markdown = await fetch_as_markdown(url, client)
await asyncio.sleep(1.0) # Polite delay
if use_llm:
contacts = extract_contacts_llm(markdown)
if contacts:
for contact in contacts:
contact['source_url'] = url
return contacts
else:
info = extract_contact_regex(markdown)
return [{
'source_url': url,
'emails': ', '.join(info.emails),
'phones': ', '.join(info.phones),
'linkedin': info.social_profiles.get('linkedin', ''),
'twitter': info.social_profiles.get('twitter', ''),
}]
except Exception as e:
return [{'source_url': url, 'error': str(e)}]
tasks = [process_url(url) for url in urls]
nested_results = await asyncio.gather(*tasks)
for result_list in nested_results:
results.extend(result_list)
return results
def save_to_csv(contacts: list[dict], output_path: str) -> None:
if not contacts:
return
fieldnames = list(contacts[0].keys())
with open(output_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
writer.writerows(contacts)
# Usage
async def main():
urls = [
"https://example-company.com/contact",
"https://another-business.com/about",
]
contacts = await extract_contacts_batch(urls, use_llm=True)
save_to_csv(contacts, "contacts.csv")
print(f"Extracted {len(contacts)} contacts, saved to contacts.csv")
asyncio.run(main())
Legal and ethical considerations: Before scraping contact information, understand the terms of service of the target site, relevant data protection laws (GDPR, CAN-SPAM, CCPA), and the intended use of the data. Collecting emails for unsolicited outreach may violate applicable laws in your jurisdiction.
Extract contact info from any web page with clean Markdown
UnWeb converts any page to clean Markdown, removing script tags, navigation, and other HTML noise that breaks contact extraction. Free tier available.
Quick Reference: Contact Extraction Tiers
- Tier 1 (regex on Markdown): Fast, cheap, works well for cleanly formatted contact pages. Use UnWeb to convert to Markdown first.
- Tier 2 (deobfuscation): Add obfuscation pattern handlers when sites intentionally hide emails.
- Tier 3 (LLM): Use Claude Haiku for team/staff pages with multiple contacts, irregular formatting, or when you need entity disambiguation.
- Always check /contact and /about: Two pages often have more than one.