Web scraping
How do I scrape schema.org structured data?
Find the script tags of type application/ld+json and parse them as JSON; for older pages, read itemscope and itemprop attributes. Both give you clean, labeled fields.
The quick answer
Many sites describe their content for search engines using the schema.org vocabulary. The most common format is JSON-LD: a <script type="application/ld+json"> block holding a JSON object with fields like name, offers.price and aggregateRating. Select those script tags, parse their text with a JSON library, and walk the objects by @type. Older pages use microdata, where the same fields are attributes (itemprop) on the visible HTML. Either way you get labeled values without guessing at class names, which is why structured data is often the most stable source on a page.
Reading JSON-LD
import json
from bs4 import BeautifulSoup as HtmlTree
def schema_nodes(markup):
tree = HtmlTree(markup, "html.parser")
for tag in tree.find_all("script", type="application/ld+json"):
try:
data = json.loads(tag.string or "")
except ValueError: # covers malformed JSON-LD
continue
stack = data if isinstance(data, list) else [data]
for node in stack:
if isinstance(node, dict) and "@graph" in node:
yield from node["@graph"]
elif isinstance(node, dict):
yield node
products = [n for n in schema_nodes(html_text) if n.get("@type") in ("Product", ["Product"])]
The function covers the three shapes you meet in practice: a single object, a list of objects, and an object with an @graph array that bundles several entities. @type can be a string or a list, which the last line accounts for.
Reading microdata
Microdata puts itemscope and itemtype on a container and itemprop on the fields inside. The value is the element's text, except for specific tags: meta uses content, a and link use href, img uses src, and time uses datetime. A short loop handles it:
def microdata_fields(scope):
found = {}
for el in scope.select("[itemprop]"):
key = el["itemprop"]
if el.name == "meta":
val = el.get("content")
elif el.name in ("a", "link"):
val = el.get("href")
elif el.name == "img":
val = el.get("src")
else:
val = el.get_text(" ", strip=True)
found.setdefault(key, val)
return found
This flat version ignores nested scopes (an offers block inside a product). For nested data, recurse into elements that carry their own itemscope, or use a ready library. Python's extruct package, for example, extracts JSON-LD, microdata, RDFa and Open Graph in one call; check its current documentation for options.
Which fields are worth reading
- Product: name, sku, gtin, brand, image, offers (price, priceCurrency, availability).
- Article: headline, datePublished, dateModified, author.
- BreadcrumbList: the category path, useful for classifying pages.
- Organization and LocalBusiness: address, opening hours, contact points.
Trust, but verify
Structured data is written for search engines, and sites do not always keep it in sync with the page. Prices may be cached, availability may lag, and ratings may be missing on some pages. For price monitoring, compare the JSON-LD price with the visible price on a sample of pages before relying on it. If they disagree, the visible one is what a customer sees. The page on price monitoring discusses data quality checks in more depth.
Common problems
- Invalid JSON. Trailing commas, HTML comments or unescaped line breaks break
json.loads. Skip the block, or clean known patterns before parsing. - Data added by scripts. Some sites inject JSON-LD after load. If the raw HTML lacks it, render the page or read the framework's data blob.
- Several products on one page. Listing pages may hold an
ItemListwith many entries; match each one to its own URL. - Empty results from a challenge page. If a bot check answered instead of the product page, there is no schema to read. Check for a CAPTCHA before parsing, and see parsing HTML with Beautiful Soup for that guard.
Why it is worth the effort
A parser built on structured data survives redesigns that break CSS selectors, because sites keep their schema stable to protect search rankings. Many teams read JSON-LD first and fall back to selectors only for fields the schema lacks.
It also makes multi-site projects cheaper. Ten shops built on ten different templates still describe a product with the same schema.org names, so one mapping from offers.price, sku and availability to your own columns covers all of them. You then write custom selectors only for the gaps, such as shipping costs or stock counts that rarely appear in the schema. Store the raw JSON-LD next to your parsed record as well; when a field looks wrong later, you can check what the site actually published without fetching the page again.
Common questions
What is the difference between JSON-LD and microdata?
JSON-LD is a separate JSON block in a script tag; microdata is attributes on the visible HTML elements. Both use the schema.org vocabulary.
Can one page have several JSON-LD blocks?
Yes. Read all of them and combine the nodes, since product, breadcrumb and organization data often sit in separate blocks.
Is the price in JSON-LD always current?
Not always. Compare it with the visible price on a sample of pages before trusting it for monitoring.
Why is there no JSON-LD in my downloaded HTML?
The site may insert it with JavaScript, or you may have received a challenge page instead of the product page.
What does @graph mean?
It is an array of linked entities inside one JSON-LD object. Iterate it to find the node with the type you need.
Keep reading
- Structured dataJSON-LD, microdata and RDFa blocks that describe a page in machine readable form, and why they are the first thing to parse.
- JSONThe text format of objects, arrays, strings, numbers, booleans and null that almost every web API speaks, with the mistakes to avoid.
- Data extractionData extraction turns raw HTML or JSON into clean, typed records with a fixed schema that downstream tools can trust.
- Price monitoringTracking public prices across many shops on a schedule, matching the same product between them and spotting changes.