How to Extract JSON-LD and Schema.org Data When Scraping (2026)
Most product pages already hand you their price, stock and ratings as Schema.org JSON-LD. Here’s how to scrape it with extruct and BeautifulSoup, clean it into one record and know when not to trust it.

Most product pages already hand you their data in a neat, machine-readable package. You just have to know where to look.
Open the source of almost any online store and search for application/ld+json. You'll usually find a block of JSON with the product name, price, currency, stock status and rating, all labelled with standard names from Schema.org. It's there for search engines, and it's often far more stable than the page's CSS classes.
This guide shows you how to scrape JSON-LD, microdata and Open Graph tags with Python, using extruct and BeautifulSoup. You'll turn the messy real-world versions into one clean product record, and you'll see where structured data quietly lies to you.
Every script below was run on November 24, 2026, against a local test page and a public scraping sandbox. The outputs you see are the real ones.
- Most product pages embed their price, stock and ratings as Schema.org JSON-LD, which survives redesigns better than CSS selectors.
- extruct reads JSON-LD, microdata and Open Graph in one call and copes with comments that break plain json.loads.
- Walk the whole tree, because many sites hide the Product inside an @graph array.
- Prices can sit in offers, priceSpecification or an AggregateOffer range, so normalize them into one record.
- Structured data can be stale or describe variants, so spot-check it against the visible page.
What Structured Data Is and Why Scrapers Love It
Structured data is metadata a site adds to its HTML so machines can understand the page without guessing. Search engines use it for rich results such as prices and star ratings. Social networks use it to build link previews.
For a scraper, that's a gift. Instead of hunting for the price inside a <span class="pdp-price__final"> that changes with every redesign, you read a field literally called price.
You'll meet three main formats in the wild:
- JSON-LD: a JSON object inside a
<script type="application/ld+json">tag. It's separate from the visible HTML and is the format Google recommends. - Microdata: attributes such as
itemscope,itemtypeanditempropsprinkled on the visible HTML elements. Common on older store themes. - Open Graph:
<meta property="og:...">tags in the head, built for link previews. The Open Graph protocol requires only four of them:og:title,og:type,og:imageandog:url.
JSON-LD and microdata usually carry Schema.org types like Product, Offer, Review, Article or BreadcrumbList. Open Graph is thinner, so treat it as a fallback.
1Why It Beats CSS Selectors (Most of the Time)
Structured data has three big advantages over parsing the visible layout:
- It survives redesigns. Sites change class names often. They change their Schema.org markup far less, because breaking it can cost them rich results in Google.
- It's already labelled and tidy. Prices usually come without currency symbols, availability as a fixed URL like
https://schema.org/InStock, and dates in ISO 8601 format. - It's often in the first HTML response. Google advises merchants to put product markup in the initial HTML for best results, so you can frequently skip a headless browser.
It isn't magic, though. Some sites leave it out, some fill it badly, and some show different numbers in the markup than on the page. We'll handle all three cases.
If you're new to parsing HTML in Python, our BeautifulSoup web scraping tutorial covers the basics this guide builds on.
Set Up Your Python Environment
You need Python 3.8 or newer. We used Python 3.13 in a fresh virtual environment:
python3 -m venv .venv
source .venv/bin/activate
pip install extruct beautifulsoup4 lxml requestsHere's what each package does:
- extruct reads JSON-LD, microdata, Open Graph, microformats, RDFa and Dublin Core from HTML. We installed version 0.18.0, the latest on PyPI. It's BSD-licensed and maintained by Zyte, the company formerly called Scrapinghub.
- BeautifulSoup (we had 4.15.0) and lxml parse HTML. extruct uses lxml under the hood.
- requests downloads pages.
To follow along, save a product page as fixture.html. Ours is a made-up running shoe with the same messy patterns you'll meet on real stores: a @graph wrapper, a price hidden inside priceSpecification, a cross-reference by @id, and a second JSON-LD block that starts with a JavaScript comment.
Method 1: Pull JSON-LD with BeautifulSoup
The simplest approach is to find every JSON-LD script tag and run json.loads() on it. No extra library is needed beyond BeautifulSoup:
import json
from bs4 import BeautifulSoup
def jsonld_blocks(html):
soup = BeautifulSoup(html, "lxml")
items = []
for tag in soup.find_all("script", type="application/ld+json"):
try:
data = json.loads(tag.string or "")
except json.JSONDecodeError as err:
print("skipped a broken block:", err)
continue
items.extend(data if isinstance(data, list) else [data])
return items
html = open("fixture.html", encoding="utf-8").read()
for item in jsonld_blocks(html):
print(item.get("@type"), "| keys:", list(item)[:4])When we ran it against our test page, this was the output:
skipped a broken block: Expecting value: line 2 column 1 (char 1)
None | keys: ['@context', '@graph']Two problems show up straight away, and both are common on real sites.
1Problem 1: Comments Break json.loads
The second block starts with // added by a theme plugin. Browsers and Google tolerate that kind of thing, but strict JSON doesn't allow comments, so Python's parser gives up and you lose the whole block.
2Problem 2: The Product Hides Inside @graph
The first block parsed fine, but its top level has no @type. Many CMS plugins put everything into one @graph array: the organization, the breadcrumbs, the website and the product. If your code only checks the top-level @type, it'll report "no product" on a page that clearly has one.
You could fix both by hand. Or you can let extruct deal with the first one and write a small helper for the second.
Method 2: Use extruct for JSON-LD, Microdata and Open Graph
extruct pulls every supported format out of a page in one call and returns a dictionary keyed by syntax. Pass syntaxes to limit it to the formats you care about, and uniform=True to get a similar shape for each one:
import extruct
html = open("fixture.html", encoding="utf-8").read()
data = extruct.extract(
html,
base_url="https://shop.example.com/p/trail-runner-2",
syntaxes=["json-ld", "microdata", "opengraph"],
uniform=True,
)
for syntax, items in data.items():
print(syntax, "->", [item.get("@type") for item in items])Output from our run:
microdata -> ['Product']
json-ld -> [None, 'WebSite']
opengraph -> ['product']Notice the difference. The block with the comment now parses, because extruct strips a leading HTML or JavaScript comment and retries with a more forgiving JSON parser when the strict one fails. We confirmed this in its source code.
The microdata came back as a clean nested object, too. extruct read the content attribute for the price, so we got "129.00" rather than the visible text 129. Stores often use a content attribute like this to give machines a cleaner value than the one shoppers see.
But the JSON-LD product still shows up as None. extruct flattens top-level lists, not @graph. You need to walk the tree yourself.
1Useful extruct Options
| Option | What it does | When to use it |
|---|---|---|
syntaxes=[...] | Limits extraction to the formats you list | Always. It's faster and skips the experimental RDFa parser |
uniform=True | Gives microdata, Open Graph and others a JSON-LD-like shape with @type and @context | When you treat several formats the same way |
base_url= | Resolves relative URLs in the markup | Pass the final page URL after redirects |
errors="log" | Logs a failing extractor instead of raising | In production, so one bad block doesn't kill the page |
return_html_node=True | Returns the HTML node for each microdata item | When you need the element's position or extra attributes |
Find Product, Offer and Review Nodes Anywhere
The reliable way to find a type is to walk every dictionary in the JSON-LD tree and match on @type. This handles @graph, nested objects and arrays in one go:
def iter_nodes(obj):
"""Yield every dict in a JSON-LD tree, including @graph members."""
if isinstance(obj, dict):
yield obj
for value in obj.values():
yield from iter_nodes(value)
elif isinstance(obj, list):
for value in obj:
yield from iter_nodes(value)
def type_names(node):
types = node.get("@type", [])
types = types if isinstance(types, list) else [types]
# "Product", "schema:Product" and "https://schema.org/Product" all count
return {str(t).rsplit("/", 1)[-1].rsplit(":", 1)[-1] for t in types}
def find_by_type(items, wanted):
return [n for n in iter_nodes(items) if wanted in type_names(n)]
def index_ids(items):
"""Map @id -> node so references like {"@id": "...#org"} can be resolved."""
return {n["@id"]: n for n in iter_nodes(items) if "@id" in n and len(n) > 1}Three details here save a lot of debugging later:
@typecan be a list. Google's own docs show["Product", "Car"]for car listings, so we always turn it into a set.- Types can be prefixed. You'll see
Product,schema:Productandhttps://schema.org/Productin the wild. We keep only the last part. - Nodes can point to each other. A product's seller may just be
{"@id": "https://shop.example.com/#org"}.index_ids()builds a lookup table so you can swap a bare reference for the full node.
The walker also returns nested nodes, so find_by_type(data, "Offer") finds the offers inside a product, and find_by_type(data, "BreadcrumbList") gets you the category path.
Turn Messy Schema.org Data into One Clean Record
Schema.org is flexible, which means two stores can describe the same price in five different ways. Your job is to fold all of them into the same output columns. Here are the variations we see most:
| Field | What you'll find | How to handle it |
|---|---|---|
| Offers | A single Offer, a list of offers, or an AggregateOffer | Take the first offer; use lowPrice and highPrice for aggregates |
| Price | price on the offer or inside priceSpecification; number or string | Check both places; convert to Decimal, not float |
| Currency | priceCurrency on the offer or its price specification | Keep the three-letter ISO 4217 code |
| Availability | https://schema.org/InStock, http://schema.org/InStock or just InStock | Keep the part after the last slash |
| Brand, author, seller | A plain string or an object with a name | Read name when it's an object |
| Image | A URL, a list of URLs, or an ImageObject | Take the first and read url if it's an object |
Google's product snippet documentation explains why so many shapes exist. A Product needs a name plus at least one of offers, review or aggregateRating. The price can sit in price or in priceSpecification.price, and an AggregateOffer uses lowPrice instead. So a valid page may have no price at all.
This normalizer copes with all of those cases:
from decimal import Decimal, InvalidOperation
def first(value):
"""JSON-LD allows one value or a list. Always hand back one value."""
if isinstance(value, list):
return value[0] if value else None
return value
def as_list(value):
if value is None:
return []
return value if isinstance(value, list) else [value]
def text(value):
value = first(value)
if isinstance(value, dict): # Brand, Person, Organization, ImageObject...
value = value.get("name") or value.get("url") or value.get("@id")
return str(value).strip() if value not in (None, "") else None
def number(value):
value = text(value)
if value is None:
return None
try:
return Decimal(value.replace(",", ""))
except InvalidOperation:
return None
def price_of(offer):
spec = first(offer.get("priceSpecification")) or {}
price = offer.get("price", spec.get("price"))
if price is None: # AggregateOffer uses lowPrice / highPrice
price = offer.get("lowPrice")
currency = offer.get("priceCurrency", spec.get("priceCurrency"))
return number(price), text(currency)
def normalize_product(node, ids=None):
ids = ids or {}
offer = first(node.get("offers")) or {}
offer = ids.get(offer.get("@id"), offer)
price, currency = price_of(offer)
rating = node.get("aggregateRating") or {}
availability = text(offer.get("availability"))
return {
"name": text(node.get("name")),
"sku": text(node.get("sku")),
"gtin": text(node.get("gtin13") or node.get("gtin") or node.get("gtin12")),
"brand": text(node.get("brand")),
"image": text(node.get("image")),
"price": price,
"high_price": number(offer.get("highPrice")),
"currency": currency,
"availability": availability.rsplit("/", 1)[-1] if availability else None,
"rating": number(rating.get("ratingValue")),
"review_count": number(rating.get("reviewCount") or rating.get("ratingCount")),
"reviews": len(as_list(node.get("review"))),
}A few choices are worth calling out:
Decimal, notfloat. Floats can't store most prices exactly, and the errors pile up when you sum or compare them.- Return
Nonerather than guess. If a value doesn't parse cleanly, an empty cell is better than a wrong price in your dataset. - Strip thousands separators, but only commas.
"1,299.00"becomes 1299.00. A European-style"12,99 €"comes back asNoneon purpose, because guessing whether the comma is a decimal point is how you end up with prices 100 times too high.
1Test It on the Edge Cases
We fed the normalizer five awkward products. Here's the trimmed output:
aggregate offer {'name': 'Box', 'price': '9.99', 'high_price': '19.99', 'currency': 'USD', 'availability': 'None', 'reviews': '0'}
type as list {'name': 'Hatchback', 'price': '18500', 'high_price': 'None', 'currency': 'EUR', 'availability': 'None', 'reviews': '0'}
prefixed type {'name': 'Lamp', 'price': '1299.00', 'high_price': 'None', 'currency': 'INR', 'availability': 'OutOfStock', 'reviews': '0'}
no offers {'name': 'Review-only item', 'price': 'None', 'high_price': 'None', 'currency': 'None', 'availability': 'None', 'reviews': '1'}
comma decimal {'name': 'Mug', 'price': 'None', 'high_price': 'None', 'currency': 'None', 'availability': 'None', 'reviews': '0'}Every case either parsed correctly or failed safely to None. That last row is exactly the kind of record you want to flag for review, not quietly store.
Extract Reviews and Ratings
Product pages often carry two kinds of review data: a summary in aggregateRating and individual entries in review. The summary gives you the average and the count. The individual reviews give you text, dates and scores.
from step4_normalize import as_list, number, text
def normalize_reviews(product):
rows = []
for review in as_list(product.get("review")):
rating = review.get("reviewRating") or {}
rows.append({
"author": text(review.get("author")) or "anonymous",
"date": text(review.get("datePublished")),
"rating": number(rating.get("ratingValue")),
"best": number(rating.get("bestRating")) or 5,
"body": text(review.get("reviewBody")),
})
return rowsOn the public sandbox we tested, the first three reviews came out like this:
{'author': 'anonymous', 'date': '2022-07-22', 'rating': Decimal('5'), 'best': Decimal('5'), 'body': 'Absolutely delicious! The orange flavor is my favorite.'}
{'author': 'anonymous', 'date': '2022-08-16', 'rating': Decimal('4'), 'best': Decimal('5'), 'body': 'I bought these as a gift, and they were well received. Will definitely purchase again.'}
{'author': 'anonymous', 'date': '2022-09-10', 'rating': Decimal('5'), 'best': Decimal('5'), 'body': 'Nice variety of flavors. The chocolate is rich and smooth.'}The author field in that markup was an empty string, so our fallback kicked in. Real stores do the same thing more often than you'd expect.
Keep in mind that the markup rarely includes every review. Stores usually embed the first few, while reviewCount reports the full total. In our sandbox test, the first product's JSON-LD listed 5 reviews and claimed 10 in total. If you need all of them, you'll have to page through the review widget or its API.
Also store bestRating alongside each score. Most sites use a 1 to 5 scale, but not all, and a 4 out of 10 isn't a 4 out of 5.
Fall Back to Microdata and Open Graph
A good extractor tries the richest source first and falls back gracefully. This pipeline tries JSON-LD, then microdata, then Open Graph, and tells you which one it used:
import json
import extruct
from step3_find import find_by_type, index_ids
from step4_normalize import normalize_product
def extract_product(html, url):
data = extruct.extract(html, base_url=url, uniform=True, errors="log",
syntaxes=["json-ld", "microdata", "opengraph"])
# 1. JSON-LD, the richest source on most sites
products = find_by_type(data["json-ld"], "Product")
if products:
return "json-ld", normalize_product(products[0], index_ids(data["json-ld"]))
# 2. Microdata, common on older themes
products = find_by_type(data["microdata"], "Product")
if products:
return "microdata", normalize_product(products[0])
# 3. Open Graph, usually just title, image and maybe price
og = data["opengraph"][0] if data["opengraph"] else {}
if og:
return "opengraph", {
"name": og.get("og:title"),
"image": og.get("og:image"),
"price": og.get("product:price:amount"),
"currency": og.get("product:price:currency"),
}
return None, {}
if __name__ == "__main__":
html = open("fixture.html", encoding="utf-8").read()
source, product = extract_product(html, "https://shop.example.com/p/trail-runner-2")
print(source)
print(json.dumps(product, indent=2, default=str))On our test page it found the JSON-LD product, followed the @graph, dug the price out of priceSpecification and returned this:
{
"name": "Trail Runner 2",
"sku": "TR2-BLK",
"gtin": "0001234567895",
"brand": "Northpeak",
"image": "https://shop.example.com/img/trail-runner-2.jpg",
"price": "129.00",
"high_price": null,
"currency": "USD",
"availability": "InStock",
"rating": "4.6",
"review_count": "212",
"reviews": 1
}Keep the source value in your output. When a site drops its JSON-LD in a redesign, you'll see the source change to microdata or opengraph in your logs before you notice missing columns.
The Open Graph branch reads product:price:amount and product:price:currency, which some stores add for link previews. Plenty of sites have only the four required tags, so expect a name and an image at best.
Run It Against a Live Page
Testing on a real site shows you the quirks a hand-made fixture misses. We used web-scraping.dev, a public sandbox built for scraping practice. Its robots.txt allows product pages and asks for a 2-second crawl delay, so we respected that:
import json
import time
import requests
from step5_pipeline import extract_product
session = requests.Session()
session.headers["User-Agent"] = "Mozilla/5.0 (compatible; structured-data-demo/1.0)"
for product_id in (1, 2, 3):
url = f"https://web-scraping.dev/product/{product_id}"
resp = session.get(url, timeout=20)
resp.raise_for_status()
source, product = extract_product(resp.text, resp.url)
print(source, json.dumps(product, default=str))
time.sleep(2) # the site's robots.txt asks for a 2-second crawl delayThe output, slightly shortened:
json-ld {"name": "Box of Chocolate Candy", "brand": "web-scraping.dev", "price": "9.99", "high_price": "19.99", "currency": "USD", "availability": "InStock", "rating": "4.7", "review_count": "10", "reviews": 5, ...}
json-ld {"name": "Dark Red Energy Potion", "brand": "web-scraping.dev", "price": "4.99", "high_price": "25.99", "currency": "USD", "availability": "InStock", "rating": "4.8", "review_count": "4", "reviews": 4, ...}
json-ld {"name": "Teal Energy Potion", "brand": "web-scraping.dev", "price": "4.99", "high_price": "25.99", "currency": "USD", "availability": "InStock", "rating": "4.8", "review_count": "4", "reviews": 4, ...}Every product came from an AggregateOffer with a price range, and no product had a SKU or barcode in its markup. That's normal. Treat SKU and GTIN as nice-to-haves, and pick a different key, such as the canonical URL, for deduplication.
We also tried a few big-brand retail product pages from our server. They returned a 429 "too many requests" or simply timed out before we got any HTML. Structured data doesn't help if you can't load the page. That part is about request rates, headers and IP reputation, which our guide to scraping e-commerce sites safely covers.
When the JSON-LD Isn't in the HTML
Some sites add their structured data with JavaScript after the page loads, so a plain HTTP request never sees it. Google supports this, though it warns that JavaScript-generated product markup can make its Shopping crawls less frequent and less reliable.
The quick test: if you can see the ld+json block in your browser's Elements panel but not in View Source, it's being injected. In that case, render the page first and then run the same extractor on the result:
import requests
from playwright.sync_api import sync_playwright
from step5_pipeline import extract_product
URL = "http://127.0.0.1:8000/js_page.html" # a test page that adds JSON-LD with JavaScript
print("raw HTML:", extract_product(requests.get(URL, timeout=20).text, URL)[0])
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(URL, wait_until="networkidle")
html = page.content() # the DOM after scripts ran
browser.close()
print("rendered:", extract_product(html, URL))Against a local test page that adds a product with JavaScript, the difference was clear:
raw HTML: None
rendered: ('json-ld', {'name': 'Desk Lamp', ..., 'price': Decimal('39.00'), 'currency': 'USD', ...})Rendering costs far more time and memory than a plain request, so only do it for sites that need it. Our guide to scraping JavaScript websites walks through the options, and the Playwright web scraping guide goes deeper on waits and selectors.
Before you reach for a browser, check the page's inline scripts too. Many modern storefronts ship their product data in a JSON blob such as __NEXT_DATA__, and that's often richer than the JSON-LD.
Don't Trust Structured Data Blindly
Structured data is written by the site, for search engines, and it can be stale, partial or simply wrong. On the sandbox's first product, the page showed "$9.99 from $12.99", a sale price. The JSON-LD reported a range of $9.99 to $19.99 across all variants. Both are true, but they answer different questions.
Build in a few checks before you store anything:
- Compare against the page now and then. Spot-check the markup price against the visible price on a sample of pages. If they drift, the site's markup is probably cached or generated separately.
- Watch for variants. Google's product variants documentation describes a
ProductGroupwithhasVariant,variesByandproductGroupID. If you see aProductGroup, loop throughhasVariantand store one row per size or color instead of taking the first price. - Check dates. A
priceValidUntilin the past is a hint the offer is stale. - Flag missing fields. Count how many records come back without a price or currency on each run. A sudden jump means the site changed something.
- Mind the currency and location. Google asks merchants to use a separate URL for each currency, but a store can still change prices by visitor location. Note which country your request came from.
Once you have clean records, our guide on how to clean and store scraped data covers deduplication, schemas and storage.
Scale It Up Responsibly
Structured data makes each page easier to parse, but it doesn't change the rules for fetching pages at scale. A few habits keep your scraper reliable and polite:
- Respect robots.txt and the site's terms. Our guide to web scraping legality and robots.txt explains what each one means for you.
- Throttle your requests. Honor any
Crawl-delay, back off on 429 errors, and read our rate limiting guide for patterns that work. - Use proxies only where they're justified. For price tracking across regions, you'll need IPs in each country you care about. Our list of the best proxies for price monitoring compares options. You can also filter providers by country in our proxy directory.
- Monitor the output, not just the job. A scraper that runs fine but returns empty prices is still broken. Scheduling and monitoring your scrapers covers alerts for this.
Store the raw JSON-LD alongside your cleaned record when you can. It's small, and when a parsing bug turns up three months later, you can rerun the normalizer without fetching a single page again.
Frequently Asked Questions
Final Thoughts
JSON-LD is one of the best shortcuts in web scraping. It gives you labelled fields that tend to outlast every redesign, and with extruct you can read it, plus microdata and Open Graph, in a single call.
The work is in the cleanup. Walk the whole tree so @graph can't hide your product. Accept that a price can live in three places. Use Decimal, return None rather than guess, and check now and then that the markup still matches the page.
Get those right and you'll have a product scraper that needs far fewer fixes than one built on CSS selectors.
Keep Reading
More articles you might enjoy


