How to Extract SEO Metadata from Websites with Python: Title, Canonical, Schema, and Open Graph
Technical SEOPythonHTML parsingJSON-LDSEO audits

How to Extract SEO Metadata from Websites with Python: Title, Canonical, Schema, and Open Graph

CCode Scrape Hub Editorial Team
2026-11-28
7 min read

Learn how to crawl websites with Python and extract titles, canonicals, robots directives, Open Graph, JSON-LD, headings, and hreflang.

Extracting SEO metadata with Python turns a crawl into an audit dataset you can filter, compare, and revisit. This guide shows how to collect titles, descriptions, canonicals, robots directives, headings, Open Graph tags, JSON-LD, status codes, and hreflang while preserving missing, duplicate, and conflicting values for investigation.

Overview

A useful SEO crawler does more than read the first matching tag. It records what the server returned, where each value came from, and whether the page contains anomalies. That distinction matters because a page may have two title elements, several canonical links, multiple JSON-LD blocks, or a canonical URL that points to a different host.

For a basic Python web scraper, requests retrieves HTML and BeautifulSoup parses it. The workflow below is appropriate for server-rendered pages and is a practical starting point for content reviews, migrations, technical SEO audits, and recurring crawls. It does not execute JavaScript. If important metadata is inserted by client-side rendering, compare the response HTML with a rendered page using a browser automation tool such as Playwright.

Before crawling, define the scope and respect the site's access rules, request limits, and applicable terms. Start with a small sample, use a descriptive user agent, add timeouts, and avoid sending requests faster than the site can reasonably handle. For broader extraction decisions, see our guide to web scraping versus APIs.

Field reference

FieldWhat to collectAudit questions
StatusHTTP status, final URL, content typeDid the request succeed, redirect, or return non-HTML content?
TitleEvery <title> valueIs one present, and is it consistent with the page?
Descriptionmeta[name="description"] valuesIs it missing, duplicated, or empty?
CanonicalEvery link[rel="canonical"] hrefIs it absolute, valid, and singular?
RobotsRobots meta values and relevant headersAre directives duplicated or contradictory?
HeadingsH1 count and heading textAre the main heading and hierarchy plausible?
Social metadataOpen Graph and selected Twitter card tagsWill shared previews use the intended title, image, and URL?
Structured dataJSON-LD text and detected typesIs the JSON valid and does it describe the page?
HreflangLanguage or region, href, and alternatesAre links complete, absolute, and mutually consistent?

Checklist by scenario

1. Set up a reproducible request

Install the basic dependencies with pip install requests beautifulsoup4. Keep the original URL, final URL, status code, response headers, and crawl timestamp in the output. Those values help distinguish an HTML problem from a redirect, timeout, access response, or parser issue.

from urllib.parse import urljoin
import json
import requests
from bs4 import BeautifulSoup

HEADERS = {
    "User-Agent": "SEO-Metadata-Audit/1.0 (contact: [email protected])"
}

def text_value(node):
    return node.get_text(" ", strip=True) if node else None

def all_meta(soup, name):
    return [tag.get("content", "").strip()
            for tag in soup.find_all("meta", attrs={"name": name})]

def extract_metadata(url):
    response = requests.get(url, headers=HEADERS, timeout=20)
    soup = BeautifulSoup(response.text, "html.parser")
    base_url = response.url

    titles = [text_value(tag) for tag in soup.find_all("title")]
    descriptions = all_meta(soup, "description")
    canonicals = [urljoin(base_url, tag.get("href"))
                  for tag in soup.find_all("link", rel=lambda value: value and "canonical" in value)]

    robots = all_meta(soup, "robots")
    headings = {
        "h1": [text_value(tag) for tag in soup.find_all("h1")],
        "h2": [text_value(tag) for tag in soup.find_all("h2")]
    }

    open_graph = {}
    for tag in soup.find_all("meta"):
        property_name = tag.get("property")
        if property_name and property_name.startswith("og:"):
            open_graph.setdefault(property_name, []).append(tag.get("content", "").strip())

    json_ld = []
    for script in soup.find_all("script", type="application/ld+json"):
        raw = script.string or script.get_text()
        try:
            json_ld.append(json.loads(raw))
        except json.JSONDecodeError:
            json_ld.append({"_parse_error": True, "raw": raw.strip()})

    hreflang = []
    for tag in soup.find_all("link", rel=lambda value: value and "alternate" in value):
        language = tag.get("hreflang")
        href = tag.get("href")
        if language and href:
            hreflang.append({"hreflang": language, "href": urljoin(base_url, href)})

    return {
        "requested_url": url,
        "final_url": response.url,
        "status_code": response.status_code,
        "content_type": response.headers.get("content-type", ""),
        "title": titles,
        "meta_description": descriptions,
        "canonical": canonicals,
        "robots": robots,
        "headings": headings,
        "open_graph": open_graph,
        "json_ld": json_ld,
        "hreflang": hreflang
    }

This example deliberately returns lists for fields that normally have one value. A list preserves evidence. You can later create audit columns such as title_count, canonical_count, and description_missing instead of silently discarding duplicates.

2. Crawl a known URL list

For an audit, begin with a URL inventory from an XML sitemap, internal-link crawl, analytics export, or application database. Store one record per URL and pause between requests. Add retry logic only for temporary failures; repeated retries against a persistent client or server error add load without improving the dataset. If the same pages are checked frequently, conditional requests and caching can reduce unnecessary downloads. See our HTTP caching guide for scrapers.

3. Handle dynamic pages separately

Requests and BeautifulSoup parse the HTML response, not the final browser DOM. If the source contains an empty shell and JavaScript later inserts the title, JSON-LD, or social tags, use a rendered crawl for those URLs. Keep the extraction method in the dataset, for example source_html or rendered_dom, so a change in results is explainable. Do not mix rendered and non-rendered values without recording the difference.

What to double-check

Titles, descriptions, and headings

Check presence, count, whitespace, and text quality rather than applying a universal character limit. A title can be present but empty, repeated across many URLs, or unrelated to the visible content. The same applies to descriptions. For headings, record all H1 and H2 text, not just a Boolean pass or fail. A page with no H1 and a page with five H1 elements require different follow-up.

Canonicals and redirects

Resolve relative canonical URLs against the final response URL with urljoin. Compare the canonical with the requested URL, final URL, and status code. Flag non-HTTP links, malformed URLs, multiple canonicals, and canonicals that point to an unexpected host or path. A redirecting page and its destination should be reviewed together rather than judged from the canonical field alone.

Robots directives

Preserve the complete content of each robots meta tag and, where relevant, the X-Robots-Tag response header. Multiple sources can make interpretation difficult, so flag duplicates for manual review. This extractor reports directives; it should not be treated as a complete crawler-policy engine.

Open Graph, JSON-LD, and hreflang

Open Graph values are often repeated, so retain all values and identify conflicts such as two og:title entries. Parse JSON-LD with Python's JSON parser rather than regular expressions. JSON-LD may be an object, an array, or an object containing an @graph; record the raw block and detected @type values. A parseable block is not automatically correct or complete.

For hreflang, preserve the language-region code exactly as supplied, resolve relative URLs, and check whether alternate pages link back to one another. Include the x-default value when present. Do not assume that a language code alone proves the page is the right regional version.

Common mistakes

  • Keeping only the first match: this hides duplicate canonicals, descriptions, and social tags. Store arrays before producing summary flags.
  • Using regex for HTML structure: regex can help with narrow text checks, but an HTML parser is safer for nested markup, attributes, and malformed documents. Our CSS selector and XPath cookbook covers more robust field mapping.
  • Ignoring status and content type: an error page, PDF, or redirect response should not be analysed as if it were the requested HTML page.
  • Overwriting missing values: distinguish missing, empty, invalid, and not checked. These states lead to different fixes.
  • Assuming source HTML is the browser DOM: compare a rendered sample when a framework inserts metadata after load.
  • Changing parser behaviour without a baseline: save representative HTML fixtures and rerun the extractor after dependency or selector changes.

After extraction, run data-quality checks for duplicates, unexpected nulls, invalid URLs, and schema changes. The scraped-data validation checklist is useful when turning raw records into an ongoing audit process.

When to revisit

Re-run the checklist before a site migration, template redesign, seasonal planning cycle, international expansion, or major content review. It is also worth revisiting when a crawl suddenly shows a rise in missing fields, unexpected redirects, JSON-LD parse failures, or changes in rendered content.

For recurring crawls, compare each run with the previous dataset instead of looking only at the latest export. Track changes to status codes, final URLs, canonical targets, title counts, robots directives, hreflang destinations, and structured-data types. Keep a small set of representative pages for regression tests: a standard article, a category page, a product or service page, a paginated page, and a page with alternate languages if applicable.

Your practical next step is to run the extractor against a limited URL sample, export the raw arrays alongside summary flags, and review a handful of records manually. Once the fields match what appears in the source and rendered page, add rate limiting, caching, validation, and scheduled execution. That turns a one-off SEO metadata scrape into a dependable dataset for technical decisions and growth work.

Related Topics

#Technical SEO#Python#HTML parsing#JSON-LD#SEO audits
C

Code Scrape Hub Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.