Extract SEO Metadata and JSON-LD from Web Pages with Python
pythonseojson-ldbeautiful-souphtml-parsing

Extract SEO Metadata and JSON-LD from Web Pages with Python

SScraper.page Editorial Team
2026-12-02
6 min read

Learn how to extract and validate title tags, canonicals, Open Graph fields, and JSON-LD from web pages with reusable Python code.

Extracting SEO metadata with Python is useful for site audits, crawl pipelines, content inventories, and debugging inconsistent markup. This guide provides a reusable Beautiful Soup workflow for collecting title tags, meta descriptions, canonical URLs, Open Graph fields, and JSON-LD, then shows how to validate missing, duplicated, malformed, or ambiguous values before storing them.

Overview

A web page can expose important search and sharing information in several parts of its HTML. The document title is usually contained in the <title> element. Descriptions and robots directives commonly use <meta> elements. Canonical URLs use a <link rel="canonical"> element, while social previews often use Open Graph properties such as og:title and og:image. Structured data is commonly embedded in <script type="application/ld+json"> blocks.

These formats are related, but they are not interchangeable. A page may have a title tag but no Open Graph title, or it may contain several JSON-LD objects representing different entities. A reliable web page metadata scraper should therefore preserve the raw values, record duplicates, and report validation issues rather than silently choosing a value that may be wrong.

The examples below use Python, requests, and Beautiful Soup. Install the dependencies in your project environment with python -m pip install requests beautifulsoup4. For permitted crawling, also set an appropriate timeout, identify your client where practical, and follow the site's access requirements. If an official endpoint is available, review the guidance in HTML Scraping vs API Access before parsing pages directly.

import json
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup


def fetch_html(url):
    response = requests.get(
        url,
        headers={"User-Agent": "MetadataAudit/1.0"},
        timeout=20,
    )
    response.raise_for_status()
    return response.url, response.text

Use response.url as the final URL because redirects can change the document location. Requests generally handles the response encoding, but if a site declares an unusual or inconsistent charset, inspect the response headers and HTML before normalizing text.

Checklist by scenario

Extracting standard SEO fields

Start with selectors that reflect the meaning of each element rather than relying on its position in the document. The following function returns lists for fields that may be duplicated, allowing validation to happen later.

def first_text(soup, selector):
    element = soup.select_one(selector)
    return element.get_text(" ", strip=True) if element else None


def all_meta_content(soup, **attrs):
    values = []
    for element in soup.find_all("meta", attrs=attrs):
        content = element.get("content")
        if content is not None:
            values.append(content.strip())
    return values


def extract_metadata(html, page_url):
    soup = BeautifulSoup(html, "html.parser")

    canonical_values = []
    for link in soup.find_all("link", rel=True):
        rel_values = [value.lower() for value in link.get("rel", [])]
        if "canonical" in rel_values and link.get("href"):
            canonical_values.append(urljoin(page_url, link["href"].strip()))

    return {
        "url": page_url,
        "title": first_text(soup, "title"),
        "meta_description": all_meta_content(soup, name="description"),
        "robots": all_meta_content(soup, name="robots"),
        "canonical": canonical_values,
        "og_title": all_meta_content(soup, property="og:title"),
        "og_description": all_meta_content(soup, property="og:description"),
        "og_url": all_meta_content(soup, property="og:url"),
        "og_image": all_meta_content(soup, property="og:image"),
        "twitter_title": all_meta_content(soup, name="twitter:title"),
        "twitter_description": all_meta_content(soup, name="twitter:description"),
    }

The urljoin call converts a relative canonical URL into an absolute URL while preserving the original page URL separately. That distinction matters when comparing canonical targets across a crawl.

Scraping JSON-LD from a page

JSON-LD appears in script elements and can contain one object, an array, or an object with an @graph array. Parse each block independently so one malformed block does not prevent the rest of the page from being analyzed.

def extract_json_ld(soup):
    records = []

    for script in soup.find_all("script", attrs={"type": "application/ld+json"}):
        raw = script.string or script.get_text()
        raw = raw.strip()
        if not raw:
            continue

        try:
            parsed = json.loads(raw)
            records.append({"valid": True, "data": parsed, "raw": raw})
        except json.JSONDecodeError as error:
            records.append({
                "valid": False,
                "error": str(error),
                "raw": raw,
            })

    return records

Do not assume that every valid JSON-LD block describes the page itself. Inspect @type, @id, and relevant properties before mapping records to entities such as an article, product, organization, or breadcrumb list. Keeping the complete parsed object makes later analysis possible without recrawling the page.

Building a crawl-ready record

Combine the standard fields and structured data with a status field and fetch timestamp. For larger jobs, save both normalized columns and the original HTML or JSON-LD where your retention and storage rules allow. This makes changes easier to investigate and supports the fixture-based testing approach described in How to Test Web Scrapers with HTML Fixtures.

What to double-check

Use a validation pass after extraction. A compact field-mapping checklist can look like this:

FieldExpected sourceChecks
Title<title>Missing value, whitespace, duplicate title elements
Descriptionmeta[name="description"]Missing value, duplicate tags, blank content
Canonicallink[rel="canonical"]Multiple links, malformed URL, unexpected host or path
Open Graphmeta[property="og:..."]Missing title, URL, image, or inconsistent values
JSON-LDscript[type="application/ld+json"]Invalid JSON, unknown structure, missing expected type

For each field, distinguish between absent, empty, duplicated, and invalid. These states lead to different fixes. For example, a page with two canonical links requires an ambiguity review, while a page with one relative canonical link may only need URL normalization in your dataset. Compare canonical and Open Graph URLs carefully: they can intentionally differ, but an unexpected difference is worth flagging.

Also check the document you actually received. A request may return a consent page, access-denied response, login screen, or JavaScript shell instead of the rendered content you expected. When results are empty or inconsistent, consult Fix Common Web Scraping Errors and record the HTTP status, final URL, content type, and response length alongside extraction results.

Common mistakes

  • Using only one selector for every metadata field. Open Graph uses the property attribute in common implementations, while standard descriptions and Twitter cards often use name. Support both patterns only when there is a clear reason, and retain the source attribute in your output.
  • Overwriting duplicates. A dictionary comprehension or select_one call can hide repeated tags. Return lists first, then apply an explicit rule for reporting or selecting values.
  • Treating JSON-LD as ordinary text. Extract the script contents and parse them as JSON. Do not use regular expressions to interpret nested objects.
  • Expecting Beautiful Soup to render JavaScript. Beautiful Soup parses the HTML supplied to it; it does not execute client-side applications. If critical metadata is added after rendering, determine whether a documented endpoint or an approved browser-rendering workflow is appropriate.
  • Discarding malformed blocks. Keep the raw JSON-LD and parsing error. A malformed block is an audit result, not merely a missing value.
  • Ignoring encoding and whitespace. Normalize surrounding whitespace, but avoid destructive transformations that alter URLs, JSON text, or meaningful punctuation. Keep raw and normalized versions when the data will be reviewed.
  • Crawling without resilience. For a multi-page job, add timeouts, retry limits, backoff, rate controls, and resumable output. The guide to reliable scraping requests covers these workflow concerns.

When to revisit

Revisit this extraction workflow before a new site audit, after a template migration, and whenever a crawl begins producing unusual numbers of missing or malformed fields. It is also worth reviewing before seasonal planning cycles if your reports compare pages over time, because template changes can alter field availability without changing the page's visible content.

Update the parser when your input sources change: a site may move metadata into a different template, introduce multiple JSON-LD entities, change URL conventions, or begin serving different HTML to different request contexts. Treat selector changes as code changes: add representative HTML fixtures, test relative and absolute URLs, include duplicate and malformed examples, and compare snapshots before deploying.

Your practical checklist is: fetch responsibly; save the final URL and response details; parse title, standard meta, canonical, Open Graph, and JSON-LD separately; preserve duplicates and raw values; validate structure and URLs; classify missing versus malformed data; test against fixtures; and record the extraction version with each crawl. This turns a one-off metadata scraper into a repeatable text and data processing workflow that can be reviewed whenever the underlying pages or tools change.

Related Topics

#python#seo#json-ld#beautiful-soup#html-parsing
S

Scraper.page Editorial Team

Developer Resources 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.