Your email scraper is missing half the emails: decoding Cloudflare protection, [at] [dot] and HTML entities in Python
The classic email scraper is one regex over the page HTML:
re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", html) Run it on a list of small business websites and you will notice two things. It misses a lot of addresses that are clearly visible on the page, and it "finds" a lot of junk like logo@2x.png. This post fixes both, with small functions you can drop into any scraper.
1. Cloudflare email protection
If a site is behind Cloudflare with "Email Address Obfuscation" on (it is on by default for many plans), the HTML your script downloads does not contain the email. Instead you get something like:
<a href="/cdn-cgi/l/email-protection#7c1f1312081d1f083c19041d110c1019521f1311">[email protected]</a> <span class="__cf_email__" data-cfemail="7c1f1312081d1f083c19041d110c1019521f1311">[email protected]</span> (Both of those decode to contact@example.com.)
A browser runs a small script that decodes it. The encoding is a simple XOR: the first byte (two hex characters) is the key, and every following byte XOR the key is one character of the email.
import re def decode_cfemail(hex_str: str) -> str: key = int(hex_str[:2], 16) return "".join( chr(int(hex_str[i:i + 2], 16) ^ key) for i in range(2, len(hex_str), 2) ) CF_RE = re.compile(r'data-cfemail="([0-9a-fA-F]+)"|/cdn-cgi/l/email-protection#([0-9a-fA-F]+)') def cloudflare_emails(html: str) -> set[str]: found = set() for attr, href in CF_RE.findall(html): hex_str = attr or href try: found.add(decode_cfemail(hex_str).lower()) except ValueError: pass return found On many small business sites this alone recovers the main contact address.
2. HTML entities and mailto links
Some sites encode the address as HTML entities so naive scrapers skip it: info@... is info@.... Others only have it in a mailto: link, sometimes URL encoded. Decode first, search second:
import html as htmllib from urllib.parse import unquote EMAIL_RE = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,24}") def plain_emails(page_html: str) -> set[str]: text = htmllib.unescape(unquote(page_html)) return {e.lower() for e in EMAIL_RE.findall(text)} 3. "name [at] domain [dot] com"
People still write addresses out to dodge spam bots. The variants are endless, but a handful of patterns cover most of them:
# Bracketed forms in any case, bare words only in capitals ("info AT acme DOT com"), # otherwise normal sentences like "meet us at noon. Contact" turn into fake emails. AT = r"(?:\s*(?i:\[at\]|\(at\)|\{at\})\s*|\s+AT\s+)" DOT = r"(?:\s*(?i:\[dot\]|\(dot\)|\{dot\})\s*|\s+DOT\s+|\.)" OBFUSCATED_RE = re.compile( rf"([a-zA-Z0-9._%+-]+){AT}([a-zA-Z0-9-]+(?:{DOT}[a-zA-Z0-9-]+)*){DOT}([a-zA-Z]{{2,24}})\b" ) def obfuscated_emails(text: str) -> set[str]: out = set() for user, domain, tld in OBFUSCATED_RE.findall(text): domain = re.sub(DOT, ".", domain) candidate = f"{user}@{domain}.{tld}".lower() if EMAIL_RE.fullmatch(candidate): out.add(candidate) return out Run this on the visible text (for example BeautifulSoup(html).get_text(" ")), not the raw HTML, or it will match things inside scripts.
4. Filter the junk
Now the opposite problem. The basic regex happily matches:
- image names:
logo@2x.png,hero@3x.webp - error tracking addresses: Sentry DSNs and similar
- placeholders:
example@example.com,your@email.com,name@domain.com - no-reply addresses that nobody reads
JUNK_TLDS = {"png", "jpg", "jpeg", "gif", "webp", "svg", "css", "js"} JUNK_PARTS = ("example.", "domain.com", "email.com", "sentry", "wixpress", "noreply", "no-reply") def is_junk(email: str) -> bool: user, _, domain = email.partition("@") tld = domain.rsplit(".", 1)[-1] if tld in JUNK_TLDS: return True if any(p in email for p in JUNK_PARTS): return True if len(user) > 40 or re.fullmatch(r"[0-9a-f]{16,}", user): return True # hash like tokens return False 5. Put it together for one website
Emails usually live on the contact, about or imprint page, not the homepage. Fetch the homepage, follow a few likely links, and run all the extractors on each page:
import requests from bs4 import BeautifulSoup from urllib.parse import urljoin, urlparse CONTACT_HINTS = ("contact", "about", "impressum", "imprint", "team", "kontakt") def find_emails(site: str, max_pages: int = 5) -> dict: if not site.startswith("http"): site = "https://" + site session = requests.Session() session.headers["User-Agent"] = "Mozilla/5.0 (compatible; contact-finder-tutorial)" home = session.get(site, timeout=20) soup = BeautifulSoup(home.text, "html.parser") host = urlparse(home.url).netloc pages = [home.url] for a in soup.find_all("a", href=True): url = urljoin(home.url, a["href"]) if urlparse(url).netloc == host and any(h in url.lower() for h in CONTACT_HINTS): if url not in pages: pages.append(url) pages = pages[:max_pages] results = {} for url in pages: page_html = home.text if url == home.url else session.get(url, timeout=20).text text = BeautifulSoup(page_html, "html.parser").get_text(" ") emails = cloudflare_emails(page_html) | plain_emails(page_html) | obfuscated_emails(text) for e in emails: if not is_junk(e): results.setdefault(e, url) # remember where each email was found return results print(find_emails("example-plumbing.com")) Keeping the page each email was found on (results[email] = url) is worth it. When someone asks "where did this address come from?", you can answer.
Being a good citizen
Respect robots.txt (Python has urllib.robotparser), keep one request at a time per site with a small delay, and follow the email and privacy laws that apply to how you use the addresses. Public business contact details are fair to collect; spamming them is not.
When a script is not enough
The functions above get you most of the way for a few dozen sites. For thousands, the remaining work is the boring part: retries, sites that only answer on www or http, timeouts, bot protection, phone number normalization, dedupe across acme.com and www.acme.com, and a clear status for each site.
That boring part is what I built the Website Contact Finder on Apify for. It returns one row per website with emails, phones in E.164, social profiles, contact form URL, address, company name and the page each item came from, and you only pay for sites where something was found (about $0.90 per 1,000 sites on the free plan at the time of writing):
from apify_client import ApifyClient client = ApifyClient("YOUR_APIFY_TOKEN") run = client.actor("zhtech/website-contact-finder").call(run_input={ "websites": ["acmeplumbing.com", "example-dental.co.uk"], "maxPagesPerSite": 6, "defaultCountry": "US", }) for row in client.dataset(run["defaultDatasetId"]).iterate_items(): print(row["domain"], row["status"], row.get("primaryEmail"), row.get("primaryPhone")) Either way, decoding the hidden addresses is the single biggest improvement you can make to an email scraper.
Disclosure: I build the Website Contact Finder mentioned at the end. Published by ZH Tech. This post was written with AI assistance and reviewed before publishing.