How to extract email addresses from a website in Python
Checked on 2026-11-19.
A company's contact addresses sit in a few predictable places: mailto: links, the text of its contact, about or imprint page, and the footer of the home page. With Requests and Beautiful Soup you can read all of them in about fifty lines of Python. What such a script does not see are addresses a site keeps from scripts on purpose, and pages that are built in the browser.
1. Requests and Beautiful Soup
The plan: fetch the home page, collect addresses from mailto: links and from the visible text, then do the same on the few pages of the site whose address looks like a contact page.
# pip install requests beautifulsoup4
import re
import time
from urllib.parse import unquote, urljoin, urlparse
import requests
from bs4 import BeautifulSoup
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
CONTACT_WORDS = ("contact", "about", "imprint", "impressum", "team")
IMAGE_ENDINGS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg")
def read(url, session):
res = session.get(url, timeout=15)
res.raise_for_status()
return res.url, BeautifulSoup(res.text, "html.parser")
def emails_in(soup):
found = set()
for link in soup.select('a[href^="mailto:"]'):
# mailto:one@example.com,two@example.com?subject=Hello
addresses = unquote(link["href"][len("mailto:"):].split("?")[0])
found.update(a.strip().lower() for a in addresses.split(",") if "@" in a)
found.update(match.lower() for match in EMAIL.findall(soup.get_text(" ")))
return {email for email in found if not email.endswith(IMAGE_ENDINGS)}
def site_emails(domain, max_pages=5):
session = requests.Session()
home, soup = read(f"https://{domain}", session)
emails = emails_in(soup)
pages = []
for a in soup.find_all("a", href=True):
link = urljoin(home, a["href"]).split("#")[0]
same_site = urlparse(link).hostname == urlparse(home).hostname
looks_right = any(word in urlparse(link).path.lower() for word in CONTACT_WORDS)
if same_site and looks_right and link not in pages:
pages.append(link)
for link in pages[: max_pages - 1]:
time.sleep(1) # one page a second is plenty
try:
emails |= emails_in(read(link, session)[1])
except requests.exceptions.RequestException:
continue
return sorted(emails)
print(site_emails("apify.com"))Three details in it matter. A mailto: link can hold several addresses separated by commas, percent-encoded and followed by ?subject=... (RFC 6068), so it is cut, decoded and split instead of taken whole. The pattern for addresses in text also matches file names such as logo@2x.png, which is why image endings are dropped. And every request has a timeout: the Requests documentation says that without one, requests do not time out.
Keep it polite. Read a handful of pages per site, pause between them, and look at the site's robots.txt first; Python's standard urllib.robotparser reads it.
Where the script stops
- Addresses hidden from scripts. Cloudflare's Email Address Obfuscation, which Cloudflare says it enables automatically when a site signs up, replaces the addresses in the HTML with
[email protected]links and restores them with a script in the visitor's browser. Your script receives the placeholder. Other sites writename [at] example [dot] comor show the address as an image. Each of these is the owner saying no to harvesters, and this guide does not show how to undo them. - Pages built in the browser. When the HTML a server sends is a shell that JavaScript fills in, there is no address in it to find. Reading such a page takes a browser automation library such as Playwright, which is slower and heavier than a request.
- Sites that refuse scripts. Some answer 403 or a challenge page to anything that is not a browser. Then there is nothing to parse.
- Noise. An address on a page is not always the company's: the agency that built the site, a quoted customer, a placeholder such as
name@example.com. Compare each address's domain with the site's. - Upkeep. Contact pages are named differently in every language, and the list of words in the script is yours to maintain.
2. An API that returns what a site publishes
The Pipefetch website contacts endpoint is the same job as one HTTPS request. It reads the home page first, then the pages most likely to hold contact details (contact, imprint, about, team), up to the number in pages: 5 by default, 10 at most.
import os
import requests
res = requests.get(
"https://pipefetch.com/v1/web/contacts",
params={"url": "apify.com", "pages": 5}, # pages: 1 to 10
headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
timeout=90,
)
if res.status_code == 404:
# no_contacts, website_unreachable or website_blocked: not charged
print(res.json()["error"]["code"])
else:
res.raise_for_status()
data = res.json()["data"]
print(data["primaryEmail"], data["contactPageUrl"])
for item in data["emails"]:
print(item["email"], item["type"], item["mxFound"], item["foundOn"])Each entry in emails has the address, a type (role for a shared mailbox such as support@), whether it is on the website's own domain (onWebsiteDomain) or at a free mail provider (freeProvider), and the pages it was found on (foundOn). The answer also carries phone numbers, social profiles, the contact page and contact form, and the postal address when the site shows one. The reference lists every field.
Where it stops: in the same place as your script on two counts. It reads pages as plain HTML, so contact details that only appear after a page runs JavaScript are not seen, and a site that refuses automated requests answers 404 website_blocked. Only what the website itself publishes is returned: nothing is guessed, and no other source is asked. What it saves you is the crawling, the filtering and the upkeep, not the limits of the web.
A request costs 1 credit and most take 2 to 9 seconds. A site with no email, phone or social profile on the pages read answers 404 no_contacts, and one that does not answer within about 20 seconds answers 404 website_unreachable; neither costs anything. A new account has 100 free credits and needs no card. This is not an official API of the websites it reads, and Pipefetch is not affiliated with them.
Which one should you use?
| Situation | Use |
|---|---|
| A few sites, once, from your own computer | The script |
| You want full control over which pages are read and how addresses are filtered | The script, extended |
| A list of company domains, a CRM that fills in contacts as accounts arrive, or code that runs on a server | An HTTP API such as Pipefetch |
| A site that hides its addresses from scripts | Neither: use its contact form |
Found is not verified
An address on a web page can be years old. Checking that its domain has mail servers catches dead domains, and that is what mxFound in the API's answer tells you. It does not confirm that a mailbox exists: no test message is sent, by the API or by the script above.
What you may do with the addresses
That an address is public does not settle what you may do with it. The European Commission's own examples draw the line: an address such as name.surname@company.com is personal data, an address such as info@company.com is not. The first kind falls under the GDPR for whoever collects and stores it.
Sending is regulated separately. In the United States, the FTC's CAN-SPAM guide says the law "makes no exception for business-to-business email", and its list of practices the law provides criminal penalties for includes "harvesting email addresses".
In practice: prefer the shared mailboxes a company publishes for the purpose, keep only what you need, honor opt-outs, and do not publish or sell lists of people's addresses. Pipefetch's terms forbid using the API to harass people or to send unlawful bulk messages. None of this is legal advice.
Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.
Free tools for this
APIs used in this guide
-
1 credit
Website Contacts API
The emails, phone numbers and social profiles a website publishes, with its contact page, address and company name.
GET /v1/web/contacts -
1 credit
Web Page to Markdown API
The content of one web page as Markdown or text, without its menus, with title, headings and word and token counts.
GET /v1/web/content
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to turn a web page into Markdown in JavaScript for RAG
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python