Glossary
Data extraction: from markup to structured records
Data extraction is the step that takes a downloaded page or API response and turns the parts you care about into clean, consistent records.
Definition
Fetching a page gives you a long string. Extraction decides which pieces of that string become fields, converts them into proper types, and checks that the result makes sense. A product page becomes {"sku": "A-1001", "price": 19.99, "currency": "EUR", "in_stock": true}. Good extraction is the difference between a dataset you can analyze and a folder of HTML.
Where the data lives
Look for the cleanest source before writing selectors:
- Background JSON calls. Many pages load their data from an API endpoint. Calling it directly gives structured data with no parsing. See hidden API scraping.
- Embedded JSON. Frameworks often ship the initial state in a script tag, and many shops include
application/ld+jsonblocks with product data. See structured data. - HTML elements. When neither exists, query the DOM with CSS selectors or XPath.
- Visible text only. As a last resort, pattern matching on rendered text.
Extracting from embedded JSON
import json
from bs4 import BeautifulSoup
def product_from_ldjson(html):
soup = BeautifulSoup(html, "html.parser")
for tag in soup.select('script[type="application/ld+json"]'):
try:
doc = json.loads(tag.string or "")
except json.JSONDecodeError:
continue
if isinstance(doc, dict) and doc.get("@type") == "Product":
offer = doc.get("offers") or {}
return {"name": doc.get("name"),
"price": float(offer.get("price", "nan")),
"currency": offer.get("priceCurrency")}
return None
Cleaning and normalizing
- Strip whitespace and invisible characters, decode HTML entities.
- Parse numbers with locale awareness: "1.299,00" and "1,299.00" mean the same amount.
- Convert dates to ISO 8601 with a time zone.
- Map free text states ("Only 2 left", "Out of stock") to a fixed set of values.
- Resolve relative URLs against the page URL.
Validation
Define a schema and check every record: required fields present, prices positive, currency from a known list. Track the share of records failing each rule per run. A sudden rise usually means the site changed its layout, or that you received a different page altogether, such as a login wall or a bot challenge. Catching that early stops bad rows from reaching reports.
Keeping the raw input
Store the raw response, or at least a compressed copy, next to each extracted record for a while. When a field looks wrong weeks later, you can rerun an improved extractor over the saved pages instead of fetching them again, and you can prove what the source showed at the time. Object storage is cheap compared with a second crawl.
When the page is a challenge
A frequent silent failure: your extractor runs on a CAPTCHA page, finds nothing, and records empty values. Check for challenge markers before extraction. If you see one, hand the URL to your solving step, for example a Cloudflare Turnstile task, and extract only from the real page you get afterwards. For image puzzles that hold text, Image to Text returns the characters directly. Failed solves cost nothing, so retrying is cheap, while silently storing an empty record costs data quality.
Common questions
What is the difference between scraping and extraction?
Scraping usually means the whole process, while extraction is the specific step of pulling fields out of fetched content.
Is embedded JSON better than HTML selectors?
Usually yes. It is already structured, changes less often than markup, and avoids fragile selectors.
How do I handle prices in different formats?
Parse them with the page locale in mind, store a numeric value plus a currency code, and keep the raw string for debugging.
How can I detect that a site layout changed?
Validate records against a schema and alert when the failure rate for a field rises above its normal level.
Why are my extracted fields suddenly empty?
Often the page was a login wall or bot challenge. Check for challenge markers before running your extractor.
Keep reading
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.
- Structured dataJSON-LD, microdata and RDFa blocks that describe a page in machine readable form, and why they are the first thing to parse.
- CSS selectorCSS selectors are the compact pattern language for picking elements by tag, class, attribute and position, and most scraping tools speak it.
- How do I read JSON from a response in Python?Call response.json() after checking status and content type, and pull JSON embedded in HTML with a parser.