{"slug": "how-to-enrich-a-company-from-a-domain-python-llm-workflow", "title": "How to enrich a company from a domain (Python + LLM workflow)", "summary": "A developer published a Python workflow for enriching company profiles from a domain name, combining Firecrawl for page fetching with OpenAI structured outputs for field extraction. The pipeline normalizes the domain, scrapes the homepage plus up to three same-domain supporting pages (about, contact, team), and validates extracted fields, with the key lesson being to let the model return null rather than guess missing data. The writeup notes that page discovery, missing data, validation and cost control—not the model—are the hard parts.", "body_md": "You have a domain. You want a clean company profile: name, description, industry, socials, contact info, location. Sounds like a one-liner. It isn't, but it's closer than you'd think.\n\nThe workflow is four steps: fetch the site, extract fields with an LLM, validate the output, and figure out the point where building your own thing stops being worth it. I'll walk through all four with real Python you can run today.\n\nStack: [Firecrawl](https://docs.firecrawl.dev/api-reference/endpoint/scrape) for fetching, [OpenAI structured outputs](https://developers.openai.com/api/docs/guides/structured-outputs) for extraction. Plain HTTP, no SDKs, so you can port it to Node, Go, or whatever you live in.\n\nThe demo everybody writes:\n\nThis works beautifully on `stripe.com`. Then your next record is a parked domain, the one after that hides its address three clicks deep, and the one after *that* is a JS app that returns an empty shell on the first request. The model is rarely the hard part. Page discovery, missing data, validation, and cost control are.\n\nThe single most useful mindset shift: **make it cheap for the model to be honest.** If the page doesn't show a phone number, the right answer is `null`, not a plausible guess that happens to match the country code.\n\n```\npip install requests\npython\nimport json\nimport os\nimport re\nfrom urllib.parse import urljoin, urlparse\n\nimport requests\n\nFIRECRAWL_API_KEY = os.environ[\"FIRECRAWL_API_KEY\"]\nOPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]\nOPENAI_MODEL = os.environ.get(\"OPENAI_MODEL\", \"gpt-5.5\")\n\nMAX_CHARS_PER_PAGE = 12000\nSUPPORTING_PAGE_LIMIT = 3\n```\n\nInput is always messier than you want. `companyenrich.com`, `https://companyenrich.com`, `www.companyenrich.com/`. Clean it up first.\n\n``` php\ndef normalize_domain_to_url(value: str) -> str:\n    value = value.strip()\n    if not value.startswith((\"http://\", \"https://\")):\n        value = \"https://\" + value\n\n    parsed = urlparse(value)\n    return f\"{parsed.scheme}://{parsed.netloc}\".rstrip(\"/\")\n```\n\nHere's a gotcha. Firecrawl's `onlyMainContent` defaults to `true`, which strips headers, navs, and footers. Great for reading articles. Terrible for enrichment, because the footer is exactly where social links and contact details live. Set it to `False`.\n\n``` php\ndef scrape_url(url: str) -> dict:\n    response = requests.post(\n        \"https://api.firecrawl.dev/v1/scrape\",\n        headers={\n            \"Authorization\": f\"Bearer {FIRECRAWL_API_KEY}\",\n            \"Content-Type\": \"application/json\",\n        },\n        json={\n            \"url\": url,\n            \"formats\": [\"markdown\", \"links\"],\n            \"onlyMainContent\": False,\n            \"removeBase64Images\": True,\n            \"blockAds\": True,\n        },\n        timeout=60,\n    )\n    response.raise_for_status()\n    return response.json()[\"data\"]\n```\n\nThe homepage alone usually isn't enough. Use the returned links to find a few supporting pages, same-domain only.\n\n``` php\ndef discover_supporting_urls(home_url: str, links: list[str]) -> list[str]:\n    home_host = urlparse(home_url).netloc.replace(\"www.\", \"\")\n    keywords = (\"/about\", \"/company\", \"/contact\", \"/locations\", \"/location\", \"/team\")\n\n    candidates = []\n    for link in links or []:\n        href = link if isinstance(link, str) else link.get(\"href\") or link.get(\"url\")\n        if not href:\n            continue\n\n        absolute = urljoin(home_url, href)\n        parsed = urlparse(absolute)\n        host = parsed.netloc.replace(\"www.\", \"\")\n        path = parsed.path.lower()\n\n        if host == home_host and any(keyword in path for keyword in keywords):\n            candidates.append(absolute.split(\"#\")[0])\n\n    return list(dict.fromkeys(candidates))[:SUPPORTING_PAGE_LIMIT]\n```\n\nThen stitch it all into one payload for the model:\n\n``` php\ndef fetch_company_pages(domain: str) -> str:\n    home_url = normalize_domain_to_url(domain)\n    pages = []\n\n    home_data = scrape_url(home_url)\n    pages.append((home_url, home_data.get(\"markdown\", \"\")))\n\n    for url in discover_supporting_urls(home_url, home_data.get(\"links\", [])):\n        try:\n            page_data = scrape_url(url)\n            pages.append((url, page_data.get(\"markdown\", \"\")))\n        except requests.RequestException:\n            continue\n\n    sections = []\n    for url, markdown in pages:\n        trimmed = (markdown or \"\")[:MAX_CHARS_PER_PAGE]\n        sections.append(f\"URL: {url}\\n\\n{trimmed}\")\n\n    return \"\\n\\n---\\n\\n\".join(sections)\n```\n\nThis is the part people get wrong. If your prompt says \"return null when the field is missing\" but your schema says `\"name\": {\"type\": \"string\"}`, you've handed the model a contradiction. It *has* to return a string, so it makes one up. Nullable fields aren't a compromise here, they're the whole point.\n\n```\nCOMPANY_SCHEMA = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"name\": {\"type\": [\"string\", \"null\"]},\n        \"domain\": {\"type\": [\"string\", \"null\"]},\n        \"description\": {\"type\": [\"string\", \"null\"]},\n        \"long_description\": {\"type\": [\"string\", \"null\"]},\n        \"industry\": {\"type\": [\"string\", \"null\"]},\n        \"founded_year\": {\"type\": [\"integer\", \"null\"]},\n        \"headquarters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"city\": {\"type\": [\"string\", \"null\"]},\n                \"country\": {\"type\": [\"string\", \"null\"]},\n                \"full_address\": {\"type\": [\"string\", \"null\"]},\n            },\n            \"required\": [\"city\", \"country\", \"full_address\"],\n            \"additionalProperties\": False,\n        },\n        \"phone\": {\"type\": [\"string\", \"null\"]},\n        \"email\": {\"type\": [\"string\", \"null\"]},\n        \"social_profiles\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"linkedin\": {\"type\": [\"string\", \"null\"]},\n                \"x\": {\"type\": [\"string\", \"null\"]},\n                \"facebook\": {\"type\": [\"string\", \"null\"]},\n                \"instagram\": {\"type\": [\"string\", \"null\"]},\n                \"youtube\": {\"type\": [\"string\", \"null\"]},\n            },\n            \"required\": [\"linkedin\", \"x\", \"facebook\", \"instagram\", \"youtube\"],\n            \"additionalProperties\": False,\n        },\n        \"evidence_urls\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n    },\n    \"required\": [\n        \"name\", \"domain\", \"description\", \"long_description\", \"industry\",\n        \"founded_year\", \"headquarters\", \"phone\", \"email\",\n        \"social_profiles\", \"evidence_urls\",\n    ],\n    \"additionalProperties\": False,\n}\nphp\ndef extract_company_profile(page_content: str) -> dict:\n    response = requests.post(\n        \"https://api.openai.com/v1/chat/completions\",\n        headers={\n            \"Authorization\": f\"Bearer {OPENAI_API_KEY}\",\n            \"Content-Type\": \"application/json\",\n        },\n        json={\n            \"model\": OPENAI_MODEL,\n            \"messages\": [\n                {\n                    \"role\": \"system\",\n                    \"content\": (\n                        \"Extract structured company data from the provided website pages. \"\n                        \"Use null when a field is not explicitly visible in the provided content. \"\n                        \"Do not guess phone numbers, email addresses, physical addresses, or social URLs. \"\n                        \"Only include evidence_urls that appear in the input.\"\n                    ),\n                },\n                {\"role\": \"user\", \"content\": page_content},\n            ],\n            \"response_format\": {\n                \"type\": \"json_schema\",\n                \"json_schema\": {\n                    \"name\": \"company_profile\",\n                    \"strict\": True,\n                    \"schema\": COMPANY_SCHEMA,\n                },\n            },\n        },\n        timeout=120,\n    )\n    response.raise_for_status()\n\n    message = response.json()[\"choices\"][0][\"message\"]\n    if message.get(\"refusal\"):\n        raise ValueError(f\"Model refused extraction: {message['refusal']}\")\n\n    return json.loads(message[\"content\"])\n```\n\nStructured outputs enforce the *shape* of the response. They do not make the values *true*. That's the next step.\n\nCheap checks first. Does the phone look like a phone? Does the LinkedIn URL point to a company page, not a person? Is that X link actually on x.com? When in doubt, `null` it.\n\n```\nPHONE_RE = re.compile(r\"^\\+?[0-9][0-9\\s().-]{6,}$\")\nEMAIL_RE = re.compile(r\"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$\")\n\ndef valid_url(value: str | None) -> bool:\n    if not value:\n        return False\n    parsed = urlparse(value)\n    return parsed.scheme in {\"http\", \"https\"} and bool(parsed.netloc)\n\ndef validate_profile(profile: dict) -> dict:\n    if profile.get(\"phone\") and not PHONE_RE.match(profile[\"phone\"]):\n        profile[\"phone\"] = None\n\n    if profile.get(\"email\") and not EMAIL_RE.match(profile[\"email\"]):\n        profile[\"email\"] = None\n\n    socials = profile.get(\"social_profiles\", {})\n\n    linkedin = socials.get(\"linkedin\")\n    if linkedin and \"linkedin.com/company\" not in linkedin:\n        socials[\"linkedin\"] = None\n\n    x_url = socials.get(\"x\")\n    if x_url and not any(host in x_url for host in (\"x.com/\", \"twitter.com/\")):\n        socials[\"x\"] = None\n\n    for key in (\"facebook\", \"instagram\", \"youtube\"):\n        if socials.get(key) and not valid_url(socials[key]):\n            socials[key] = None\n\n    profile[\"social_profiles\"] = socials\n    return profile\n```\n\nConservative on purpose. A `null` is annoying. A fake phone number in your CRM is a support ticket.\n\n``` php\ndef enrich_company_from_domain(domain: str) -> dict:\n    page_content = fetch_company_pages(domain)\n    raw_profile = extract_company_profile(page_content)\n    return validate_profile(raw_profile)\n\nif __name__ == \"__main__\":\n    company = enrich_company_from_domain(\"companyenrich.com\")\n    print(json.dumps(company, indent=2))\n```\n\nSample output:\n\n```\n{\n  \"name\": \"CompanyEnrich\",\n  \"domain\": \"companyenrich.com\",\n  \"description\": \"API-first B2B data platform for company and people intelligence.\",\n  \"industry\": \"B2B data infrastructure\",\n  \"founded_year\": null,\n  \"headquarters\": { \"city\": \"Ankara\", \"country\": \"Turkey\", \"full_address\": null },\n  \"phone\": null,\n  \"email\": null,\n  \"social_profiles\": {\n    \"linkedin\": \"https://www.linkedin.com/company/companyenrich\",\n    \"x\": null, \"facebook\": null, \"instagram\": null, \"youtube\": null\n  },\n  \"evidence_urls\": [\"https://companyenrich.com\"]\n}\n```\n\nNotice how much is `null`. That's not failure, that's honesty. The site simply doesn't publish those fields.\n\nThe biggest DIY mistake is treating missing data as a model bug when the source page just doesn't contain it.\n\n| Field | Reliability | Notes | \n|---|---|---|\n| Name | High | Usually right there on the homepage | \n| Description | High | Hero or meta description | \n| Industry | Medium | Often inferred, flag confidence | \n| Founded year | Low-medium | Frequently missing | \n| HQ city | Medium | Footer or contact page | \n| Full address | Low | Lots of SaaS sites omit it | \n| Phone / Email | Low | Often hidden behind a form | \n|  | High | Validate company vs personal | \n| Technologies | Out of scope | Needs a tech-detection source | \n\nA website tells you what a company says about itself. It can't reliably give you headcount, revenue, funding, tech stack, or historical changes. For those you need other sources, and that's exactly where DIY extraction ends and production enrichment begins.\n\nThe first 10 domains feel free. The next 10,000 teach you where the cost actually lives.\n\nGive every scrape a status instead of a silent failure: `success`, `blocked`, `timeout`, `parked`, `redirected`, `empty_content`. A blocked site and a company-with-no-phone are very different things and should never look the same in your data.\n\nFor cost control, send the *smallest useful* set of pages, not the whole site. Good defaults: homepage plus up to 3 supporting pages, 8k-15k chars each, no base64 images, no blog archives.\n\nNot \"DIY bad, API good.\" The honest version:\n\nBuild it once to understand the workflow. Buy it when the workflow becomes infrastructure. If you reach that point, a [company enrichment API](https://companyenrich.com/product/company-enrichment-api) pulls from registries, maps, filings, and tech detection on top of the website, which is what fills the gaps a homepage-only flow never can. (Full disclosure: that's the product I work on.)\n\nKeep it boring. Use public business info for legitimate business workflows. Don't scrape private areas, don't infer sensitive personal attributes, respect robots and rate limits. And separate company-level enrichment from person-level enrichment: a domain identifies a company, it isn't a license to harvest every individual you can find. If you store personal data, loop in your legal team on GDPR/CCPA.\n\n`null` instead of guessing\nThat's the whole thing. The model is the easy part. The validation layer and the build-vs-buy call are what actually decide whether your enrichment is trustworthy.\n\nIf you build this, drop your `null` rate in the comments. Curious how different stacks compare.\n\n*I'm founder of [CompanyEnrich](https://companyenrich.com), an API-first B2B data platform for company and people intelligence. We spend a lot of time on exactly the messy parts above: page discovery, multi-source enrichment, and validation at volume. If you'd rather not maintain your own extraction stack, that's what we build.*", "url": "https://wpnews.pro/news/how-to-enrich-a-company-from-a-domain-python-llm-workflow", "canonical_source": "https://dev.to/amiralinu/how-to-enrich-a-company-from-a-domain-python-llm-workflow-2872", "published_at": "2026-12-01 20:27:46+00:00", "updated_at": "2026-12-01 20:43:52.862428+00:00", "lang": "en", "topics": ["ai-tools", "large-language-models", "ai-agents", "developer-tools"], "entities": ["Firecrawl", "OpenAI", "Python"], "also_reported_by": [], "takeaway": "Set Firecrawl's onlyMainContent to false for enrichment, since stripping footers and navs removes the social links and contact details you need, and prompt the model to return null instead of guessing missing fields.", "recommendation": {"advice": "Allow the model to return null for absent fields and validate outputs before trusting them; guessing phone numbers or addresses from context produces plausible but wrong records.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/how-to-enrich-a-company-from-a-domain-python-llm-workflow", "markdown": "https://wpnews.pro/news/how-to-enrich-a-company-from-a-domain-python-llm-workflow.md", "text": "https://wpnews.pro/news/how-to-enrich-a-company-from-a-domain-python-llm-workflow.txt", "jsonld": "https://wpnews.pro/news/how-to-enrich-a-company-from-a-domain-python-llm-workflow.jsonld"}}