Clean scraped data with transforms: prices, URLs, whitespace and IDs
Clean scraped data where it is extracted: prices as numbers, absolute URLs without tracking parameters, tidy text and IDs cut from links, with named transforms.
- Published
- Reading time
- 9 min read
- By
- ExtractHub team
- data cleaning
- web scraping
- transforms
- extractors
- tutorial
On this page
Raw scraped values are messy. A price arrives as "$1,299.00", a title carries a newline and four spaces, a link is relative and drags utm_source behind it, and the product ID you need is buried in the middle of a URL. When every consumer cleans it again, each does it a little differently.
This post shows how to clean scraped data at the point of extraction, with the transforms of an ExtractHub extractor: what each common transform does, how chains behave on lists, the traps (such as toNumber on a price with a currency symbol), and how cleaning interacts with required fields and versions. Every behaviour below comes from the extraction engine’s code.
Why clean scraped data inside the extractor
An extractor is a JSON definition: request options plus a list of fields, each with a selector, an extract type and an optional transforms array. The engine applies the chain on the server, so the realtime API, the Batch API, pipelines and MCP callers all receive the same cleaned values.
Cleaning there has three effects:
- The output schema gets real types. When a version is released, ExtractHub derives an output schema from the config. A field ending in a number transform such as
extractPriceis typed as a number,toBooleanas a boolean,splitas an array. Callers can rely onpricebeing a number instead of guessing. - Empty means empty. A transform that cannot read a value returns
null. Combined withrequired, that turns a page that did not parse into a clear error instead of a row of junk (more on that below). - One place to fix. When the site changes its price format, you change one chain and release a patch, instead of patching every script that reads the data.
How a transforms chain runs
transforms is an array applied left to right, and every transform runs exactly once. An entry is either a name ("trim") or, for the transforms that take options, an object with exactly one key: the transform name ({ "split": "·" }).
{ "name": "title", "selector": "main h1", "extract": "textContent", "transforms": ["normalizeWhitespace"] }
Where the chain runs depends on the field shape:
- A single value (a field with
selector, and each sub-field of a list item): the chain runs once on that value. - An array of values (
isArray: truewithselector): value transforms such astrimorextractPricerun on each element. From the first array transform on (first,last,nth,unique,compact,joinWithComma,joinWithSpace,coalesce), the rest of the chain runs once on the whole array.["extractPrice", "compact", "first"]therefore parses every price, drops the ones that failed, and returns the first number. - JSON fields (a JSON API, or embedded JSON in a script tag): every transform runs once on the value at the path; a
[*]path gives an array.
String transforms leave non-strings alone (null stays null, a number passes through), so chains are safe on JSON values that are sometimes already numbers.
Text: whitespace, entities and markup
textContent already collapses runs of whitespace and decodes HTML entities the way a browser does. What it can leave behind is padding at the edges, which is why most text fields end with one of these:
trim: strip leading and trailing whitespace.normalizeWhitespace: trim and collapse every whitespace run to one space." Example\n headphones "becomes"Example headphones". The safe default for titles and names.stripWhitespace: remove all whitespace, for codes such as SKUs printed with spaces.
For values that are not plain text, decodeHtml decodes entities in innerHTML or JSON strings, removeHtmlTags strips tags, and toMarkdown turns an innerHTML article body into Markdown that keeps its headings, lists and links.
Convert scraped prices to numbers: extractPrice, not toNumber
The number transforms differ in what they accept, and mixing them up is a common cleaning bug:
| Transform | Input | Output |
|---|---|---|
toNumber | "19.99", "1,299.00" | 19.99, 1299 |
toNumber | "$1,299.00" | null |
extractPrice | "$1,299.00" | 1299 |
extractPrice | "EUR 1.234,56" | 1234.56 |
extractNumber | "4.5 out of 5 stars" | 4.5 |
parseCompactNumber | "2.5k" | 2500 |
toNumber removes commas and parses what is left, so anything in front of the number (a currency symbol, a word) makes it return null. It is the right choice when the value is already numeric text, such as a content attribute (<meta itemprop="price" content="1299.00">) or a JSON string like "1299.00".
extractPrice is the choice for prices as people read them. It finds the first number in the text, ignores currency symbols and codes, and decides which separator is the decimal mark: with both . and , the last one is the decimal, a lone separator followed by groups of three digits is a thousands separator, and a minus glued to the number or its currency makes it negative. When you know the convention for certain, extractNumberDotThousands (1.234,56) and extractNumberCommaThousands (1,234.56) apply it without guessing.
extractNumber takes the first number in US style, which suits counts and ratings: "1,234 reviews" becomes 1234. toInteger works like toNumber but keeps only the integer part.
A trap on the other side: a phone number, postcode or product ID is not a number. Converting "00421" to an integer silently drops the leading zeros. Keep identifiers as strings; extractDigits keeps only the digits of a string and still returns a string.
URLs: absolute links without tracking parameters
Links are usually relative in the HTML (/p/12345). toAbsoluteUrl resolves them against the URL of the page that was fetched, so the output is always a full URL that a caller can request. It works on a single value and on an array of links, which makes it the standard last step for every href and src field.
Links also collect campaign and click-tracking parameters, which make the same product look like different URLs and break deduplication. removeQueryParams removes the parameters you name; a name ending in * matches a prefix. An illustrative example:
{ "name": "url", "selector": "h2 a[href]", "extract": "attributeValue", "attributeName": "href",
"transforms": ["toAbsoluteUrl", { "removeQueryParams": ["utm_*", "fbclid"] }] }
"/p/12345?utm_source=news&color=blue&fbclid=abc#reviews" on https://www.example.com becomes "https://www.example.com/p/12345?color=blue#reviews": the parameters that matter stay, the fragment is kept, and the ? disappears when nothing is left.
Cutting values apart: split, after, before, between, nth
Values often need to be cut out of a larger string: an ID inside a URL, a category in a breadcrumb, the part of a title before the brand. There is no regex transform; instead, a handful of transforms take options and match plain text (case-sensitive). Each has a shorthand and a full form.
between takes the text after the first start, up to the next end. For an illustrative product link https://www.example.com/p/12345/example-headphones:
{ "name": "productId", "selector": "h2 a[href]", "extract": "attributeValue", "attributeName": "href",
"transforms": ["toAbsoluteUrl", { "between": ["/p/", "/"] }] }
The result is "12345". Without start the value becomes null; without an end after it, you get the rest of the string.
after and before cut at the first occurrence of a text, or the last one with "last": true. An element id="product-12345" read with attributeValue gives "12345" with { "after": "product-" }. A title written as "Example headphones - Example Brand" keeps only the product name with { "before": { "text": " - ", "last": true } }. Both return null when the text is not there, which is what you want: a wrong cut never looks like a valid value.
split turns a string into an array of trimmed parts and drops empty ones (the full form adds a limit). nth picks one element, 1-based, with negative indexes counting from the end. Together they read structured text lines. For a breadcrumb such as Home › Audio › Headphones:
{ "name": "category", "selector": "nav.breadcrumb", "extract": "textContent",
"transforms": ["normalizeWhitespace", { "split": "›" }, "last"] }
That gives "Headphones"; { "nth": 2 } instead of last would give "Audio". On an isArray field nth is an array transform, so ["trim", { "nth": 2 }] trims each element and then picks the second one.
The plain-name extractPhone belongs here too: it returns the first phone-like run with 7 to 15 digits, as written. "Call us: +1 (555) 010-0100 (Mon-Fri)" becomes "+1 (555) 010-0100", and a text without one gives null.
Options are validated when you save. A typo or a bad option is rejected with unknown_transform or invalid_transform_options and the path of the entry, for example extractorConfig.fields[2].transforms[1], before anything runs.
Lists: compact, unique, first
An isArray field returns one entry per matched element, and an element with no text gives null. Typical chains:
["toAbsoluteUrl", "compact", "unique"]for image galleries: absolute URLs, no empty entries, no duplicates (many galleries repeat the main image as a thumbnail).["extractPrice", "compact", "first"]for a price that may sit in one of several elements: the first one that parses. An empty array givesnull.
Booleans: prefer exists over toBoolean
toBoolean returns true only for "true", "1", "yes" and "on"; any other string is false. A stock label such as "In stock" becomes false, which is wrong. For flags, point a selector at the element that signals the state and use extract: "exists", which returns true or false depending on whether anything matched. An illustrative example for a page that marks availability with schema.org microdata:
{ "name": "inStock", "selector": "[itemprop=\"availability\"][href$=\"InStock\"]", "extract": "exists" }
Structured data also survives a redesign better than display text; the post on robust selectors covers picking such hooks.
Cleaning, required fields and versions
Two rules connect cleaning to the rest of the extractor.
A failed transform makes a value empty, and required notices. The required check runs on the final, transformed value. When a top-level field marked required: true comes back null, "" or [], the request fails with 422 required_fields_missing. When a required sub-field of a list item is empty, that item is dropped from the list. So if extractPrice cannot read the price on a challenge page or a broken layout, a required price turns the problem into an explicit error instead of a row with a missing price. Mark only the few fields that prove the page was parsed.
Types are part of the contract. Because the output schema is derived from the transforms, changing a field’s type is a breaking change: replacing normalizeWhitespace with extractPrice turns a string into a number, and adding split turns a value into an array. Both need a new major version, and callers pinned to the old major keep the old shape. A change that keeps the type, such as a different separator in split, is released as a patch. The post on versioned web scrapers explains pinning and majors in detail. In practice: decide the types before the first release.
Test the chain before you release
You do not need a live request to see what a chain produces. In Extractor Studio, the transform picker lists every transform, with inputs for the options of split, between and the others. With the MCP server connected, an agent runs validate_extractor_config with a saved copy of the page: it runs the real extraction engine on that HTML, without fetching and without credit, and returns what each field extracted along with any validation errors. The extractor builder skill follows the same habits described here: numbers as numbers, absolute links, attributes instead of display text where possible.
A short checklist per field: text ends with normalizeWhitespace, prices use extractPrice, links end absolute without tracking parameters, IDs stay strings, flags use exists, and every type is one you want callers to depend on for a whole major version.
The extract endpoints, response shapes and error codes are listed in the API reference.
FAQ
How do I clean scraped data?
Clean each value where it is extracted, not in every consumer. In an ExtractHub extractor each field has a transforms chain that runs left to right on the extracted value, so prices come out as numbers, links as absolute URLs and text without stray whitespace, for every caller.
How do I convert a scraped price string to a number?
Use extractPrice rather than toNumber. toNumber only removes commas, so a currency symbol in front makes it return null, while extractPrice finds the number inside the text and works out which separator is the decimal mark.
How do I remove tracking parameters from scraped URLs?
Make the link absolute with toAbsoluteUrl, then add removeQueryParams with the names to drop, such as utm_* (a trailing * matches a prefix) and fbclid. The other parameters and the fragment are kept.
Can I use a regular expression to clean scraped values?
Not in ExtractHub extractors. Transforms are a fixed list of named functions, plus split, after, before, between, nth and removeQueryParams, which take options and match plain text. They cover most cutting and splitting jobs without running user regex.
Does changing a transform break the callers of my scraper?
Only when it changes the output type. Going from a string to a number, or from one value to an array, is a breaking change and needs a new major version. A change that keeps the type, such as a different split separator, is released as a patch.
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