Fail fast when a scraped page did not parse: required fields in web scraping
Required fields in web scraping turn a page that did not parse into a 422 error instead of a half-empty row, drop incomplete list items and number the rest.
- Published
- Reading time
- 8 min read
- By
- ExtractHub team
- web scraping
- data quality
- error handling
- extractors
- tutorial
On this page
A scraper that returns { "title": null, "price": null } with HTTP 200 is worse than one that fails. The page might have been a challenge page, a consent wall, a half-rendered shell or a new layout, and your code stores the row anyway. You find out weeks later, from a report full of blanks.
This post shows how to make a scraper fail fast with required fields in web scraping: what counts as empty, what a failed request looks like, how required sub-fields filter list items, how includePosition numbers what is left, and how to handle the error in realtime calls, batches and pipelines. The examples use ExtractHub extractors, and every behaviour below is checked against the extraction engine’s code.
Why required fields in web scraping beat checking for nulls later
Every consumer of scraped data can check for nulls. In practice each one checks different fields, some forget, and none of them can tell a product without a rating (normal) from a product page that never loaded (broken). The extractor is the one place that knows which values must exist on every page of its kind.
In an extractor, each field can carry required: true. The flag means one thing: this value is present on every valid page of this type. If it is empty, the page is not a valid page, and the result should not be returned as if it were.
Good candidates are the one to three values that prove the page was parsed: a product’s title and SKU, an article’s headline, the main list on a category page. Bad candidates are values a valid page may lack: ratings, discounts, sale prices, secondary images. Marking those required turns normal data into failed requests. The scraper monitoring post goes deeper into choosing the list, because health checks judge the same flag.
What counts as an empty value
The check runs on the final extracted value, after the field’s transforms. A value is missing when it is:
null(no element matched, or a transform could not read the text),undefined,- an empty string
"", - an empty array
[].
0 and false are values. A field that counts matches (extract: "count") and returns 0 passes, and so does an exists field that returns false. An object is a value too, even when its own keys are empty; to require parts of an object, mark its sub-fields required (next sections).
Because transforms run first, a cleaning step that fails also trips the check. extractPrice returns null when the text holds no number, so a required price fails on a page that prints “Price on request”. That is usually what you want; if not, leave the price optional. The post on cleaning scraped data covers which transforms return null.
Grouped fields (group.into) are checked where their value ends up: inside the group object for the nest strategy, and as the merged list for merge.
Top-level required fields fail the request
An illustrative example product extractor for an imaginary shop on example.com (the selectors fit no real site):
{
"fields": [
{ "name": "title", "selector": "main h1", "extract": "textContent", "transforms": ["normalizeWhitespace"], "required": true },
{ "name": "sku", "selector": "[itemprop=\"sku\"][content]", "extract": "attributeValue", "attributeName": "content", "required": true },
{ "name": "price", "selector": "[itemprop=\"price\"][content]", "extract": "attributeValue", "attributeName": "content", "transforms": ["toNumber"] },
{ "name": "rating", "selector": ".rating-value", "extract": "textContent", "transforms": ["extractNumber"] }
]
}
title and sku are required; price and rating are not. You call the released version as usual:
curl -X POST "https://api.extracthub.io/api/extractor/extract" \
-H "X-API-Key: $EXTRACTHUB_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"extractor_id": "@you/example-product@1",
"target": { "url": "https://www.example.com/p/1001" }
}'
On a normal product page you get 200 with result.extracted holding the four keys; a missing rating is just null. When the page comes back without a title and SKU, the request fails with 422:
{
"success": false,
"error": "Required fields missing on the fetched page: title, sku",
"errors": [
{
"code": "required_fields_missing",
"message": "Required fields missing on the fetched page: title, sku",
"fields": ["title", "sku"],
"hint": "The page may be a challenge page, a consent wall or a different layout; retry later or check a live sample."
}
],
"requestId": "..."
}
fields lists every missing required field in the order of the config, so you can log which part of the page failed without parsing the message.
Is a failed required check charged?
The check can only run after the page was fetched. ExtractHub’s charging rule is that a request which fails after the scraping proxy was called is charged in full, and this one is no exception. When that happens the error body also carries top-level charged: true, the cost and a note explaining why. A request with useProxy: false (a direct fetch, no proxy) that fails the check is free. Prices per tier are in the pricing section.
That cost is the reason to keep the required list short. Each wrongly required field turns valid pages into charged failures.
Required sub-fields drop incomplete list items
On a list page, the same flag on a sub-field does something different. It never fails the request; it removes the item:
{
"name": "products",
"selector": "main [data-testid=\"product-card\"]",
"isArray": true,
"extract": "innerHTML",
"required": true,
"includePosition": true,
"subExtractor": {
"fields": [
{ "name": "title", "selector": "h2", "extract": "textContent", "transforms": ["normalizeWhitespace"] },
{ "name": "url", "selector": "h2 a[href]", "extract": "attributeValue", "attributeName": "href", "transforms": ["toAbsoluteUrl"], "required": true },
{ "name": "price", "selector": ".price", "extract": "textContent", "transforms": ["extractPrice"] }
]
}
}
Say the page holds four cards, and the second is a promotional tile with no link. Without required on url, you would get four items, one of them with "url": null. With it, the promo tile is gone and three products remain. This is the right tool for list pages that mix real items with ads, placeholders or “sold out” stubs that lack the key you need.
The rules, from the engine:
- In a list (
isArray), an object missing a required sub-field is dropped. - As a single value (no
isArray), the object becomesnull. - It never fails the request on its own. If every card loses its URL because the link selector broke, the list comes back
[]. That is why the list above is alsorequired: trueat the top level: an empty main list then fails with422instead of looking like a category with no products.
The same rules apply to JSON sources (subFields and subExtractor fields of a [*] path) and to lists read from embedded JSON in a script tag.
Number the remaining items with includePosition
includePosition: true on a list of objects adds a position key, 1-based, as the first key of each item. Positions are numbered after the required-item filter, so with the promo tile dropped the output is:
{
"products": [
{ "position": 1, "title": "Example laptop 13", "url": "https://www.example.com/p/1001", "price": 899 },
{ "position": 2, "title": "Example laptop 15", "url": "https://www.example.com/p/1002", "price": 1099 },
{ "position": 3, "title": "Example tablet", "url": "https://www.example.com/p/1003", "price": 499 }
]
}
(Illustrative values.) The positions are always 1..n of the items you receive, with no gaps. They match the item’s rank on the page only when nothing was dropped; if you need the raw rank including ads, leave the sub-field optional and filter in your own code.
Validation rejects two mistakes before you can save: includePosition on a field that is not a list of objects (position_needs_object_list, a list of plain strings cannot take a position), and a sub-field already named position (position_name_collision).
Handle required_fields_missing in your code
Realtime calls
The realtime API does not retry this error for you. Decide per use case: for a single lookup, show “page not available” and keep the previous value; for a sync job, skip the row and count it. A retry is a new request and, through the proxy, a new charge, so retry later rather than in a tight loop, as the hint suggests.
A minimal Node.js handler (illustrative):
const res = await fetch("https://api.extracthub.io/api/extractor/extract", {
method: "POST",
headers: { "X-API-Key": process.env.EXTRACTHUB_API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ extractor_id: "@you/example-product@1", target: { url } }),
});
const body = await res.json();
if (res.ok) {
await saveProduct(body.result.extracted);
} else {
const err = body.errors?.[0];
if (res.status === 422 && err?.code === "required_fields_missing") {
// The page was not a valid product page: do not store a row of nulls
await markForLaterRetry(url, { missing: err.fields, requestId: body.requestId, charged: body.charged === true });
} else {
throw new Error(`${res.status} ${err?.code}: ${err?.message}`);
}
}
Branch on errors[0].code, never on the message text. The API reference lists the other codes.
Batches and pipelines
In the Batch API, a URL whose required fields are empty is treated like a target-side failure: it is retried once, and if it fails again the result line says so:
{"index":7,"url":"https://www.example.com/p/1008","status":"failed","cost":<USD charged>,"error":{"code":"required_fields_missing","message":"Required field missing on the fetched page: sku"}}
The cost on the line is what that URL was charged. A URL that needed the retry is still charged once, not twice. In pipelines, an extractor step gets one more attempt inside the step for the same error, then fails that URL with the same code.
Required changes are major versions
required is part of the version’s output schema: a required node is never empty while its container is present. Changing it in either direction is a breaking change and needs a new major version. Optional to required turns requests that used to succeed into 422 failures and drops list items; required to optional lets empty values back in where callers relied on a value. includePosition follows the usual added / removed rule: adding it is a minor release, removing it a major one. The versioning post explains how pinned callers on @1 are protected from that.
Releasing also checks the flag. The release gate runs the extractor on a sample page and blocks the release when a required field has no value there, so you cannot ship a version that fails on its own sample.
When you build extractors with an agent, the extractor builder skill follows the same rules: it marks the few fields that prove the page was parsed, leaves the rest optional, and marks the main list of a list page required.
A short checklist
- Mark required only the one to three values every valid page has.
- On list pages, require the main list and the one sub-field that identifies an item.
- Remember that transforms run first: a failed
extractPriceis an empty value. - Add
includePositionwhen order matters; positions count the items returned. - In client code, branch on
required_fields_missingand store nothing for that page. - Pick the required set before the first release: changing it later is a new major.
FAQ
What is a required field in web scraping?
A field that must have a value on every page of its kind, such as the title or ID of a product page. In an ExtractHub extractor, a top-level field with required: true makes the request fail with 422 required_fields_missing when it comes back empty, instead of returning a result with nulls.
Does an empty required field still cost credit?
When the page was fetched through the scraping proxy, yes: the check runs after the fetch, so the request is charged like any other failure after a fetch, and the error body says so with charged: true. A direct request without the proxy is free when it fails.
What happens when a sub-field of a list item is required?
The item is dropped from the list instead of failing the request. A single object missing a required sub-field becomes null. Mark the list itself required too if an empty list should fail the request.
Do 0 and false count as missing values?
No. Only null, an empty string and an empty array count as missing. 0 and false are values, and so is any object.
Is making a field required a breaking change?
Yes. In ExtractHub both directions are a new major version: optional to required turns some successful requests into failures, and required to optional lets empty values back in where callers relied on a value.
Related
- Build a job listings scraper: list pages, JobPosting JSON and dedupe by URL: Build a job listings scraper that returns structured JSON: job URLs from list pages, JobPosting fields and ISO dates from each job page, and dedupe by URL.
- Build a price monitoring scraper: product fields, daily runs and change detection: Build a price monitoring scraper: a product extractor with typed prices, daily batch or scheduled runs, a signed webhook and change detection in your code.
- Use ready-made web scrapers instead of writing one: find, check and pin a public extractor: Use ready-made web scrapers instead of writing one: find a public extractor, read its fields, price tier and health, pin a version and call it with your key.
- Agent skill: install the extractor builder skill for Claude Code
- MCP server: connect Claude Code, Cursor or any MCP client
- API reference: realtime extract, async jobs and the Batch API
- Web scraper catalog: public extractors you can call today