Behavior: Starts a new Extractor group on the ScraperBuilder at top level, or a relative nested each(...) extractor when placed inside { ... }.
selector (string, required): CSS selector. Passing "" targets the root node (at top level) or current node (inside { ... }). Invalid CSS syntax throws std::runtime_error at parse time.
key (string, default ""): Optional dot-path (e.g., "product.items") under which this extractor’s output is merged.
Caveats:
At top level, select queries from the document root. If selector matches 0 nodes, that extractor is skipped (though subsequent top-level dict/JSON transforms and finalize { ... } still run).
Inside { ... }, a nested select(...) { ... } or $(...) { ... }requires a { ... } block and compiles to each(...), querying relative to the current node.
Example: $("div.card", "cards") { find(".title") | trim -> "title" }
text(own_text=false)
Behavior: Extracts text from the current Node and appends it to values.
own_text (bool, default false): When false, extracts full recursive subtree text (node.Text()). When true, extracts only direct text-node children (node.OwnText()).
Caveats: Appends "" if node is invalid or has no text.
Behavior: Extracts attribute attr_name (string or list<string>) from the current Node and appends it to values.
When attr_name is a single string, appends node.Attribute(attr_name).value_or("").
When attr_name is a list of strings (fallback mode), checks each attribute name in order and appends the first non-empty attribute value (or "" if none match).
selector (string, required): CSS selector matched via zero-allocation pre-order DFS from the current Node (or NextSiblings() when type is Value.Adjacent).
type (Value enum, optional): Defaults to Value.Text, or automatically defaults to Value.Attribute when attr is non-empty and type is omitted/null. Supports Value.Text (Text/text), Value.OwnText (OwnText/own_text), Value.Attribute (Attribute/attr), Value.ElementExists (ElementExists/exists), Value.AttributeExists (AttributeExists/attr_exists), and Value.Adjacent (Adjacent/adjacent).
attr (string | list<string>, default ""): Attribute name or fallback list for Value.Attribute / Value.AttributeExists.
required (bool, default false): Optional by default (0 matches appends nothing and leaves existing values intact). When true, throws std::runtime_error if no match yields a non-empty value (ignored for ElementExists / AttributeExists, which always push "true"/"false").
Behavior: Stops traversal immediately upon finding the first matching descendant that produces a non-empty value and appends that single value to values.
Parameters: Same as find, except squish defaults to false.
Behavior: Evaluates selector relative to the current Node (or NextSiblings() when type is Value.Adjacent) and appends every matching non-empty value to values (or "true"/"false" for ElementExists/AttributeExists).
Caveats: Optional by default (required=false); passing required=true makes 0 matches for non-existence types throw std::runtime_error.
Example: $("body") { find_all("a.tag") | trim -> "tags" }
extract_fields(spec, allow_empty=false) / fields
Parameters:
spec (object, required): Map of {output_key: selector_string_or_field_spec} where each value is either a CSS selector string ("h1") or an options object {sel|selector, type, attr, squish, trim, first, cast|as|to, default, join}:
sel / selector (string, required): CSS selector.
type (Value, default Value.Text, or Value.Attribute automatically if attr is specified without type).
attr (string | list<string>): Attribute name or fallback list.
trim (bool, default false): Trim leading/trailing ASCII whitespace when squish=false.
first (bool, default true): Stop after the first matching element (true) or collect all matches (false).
cast / as / to (string, default "string"): Type coercion ("string", "int", "float", "number", "bool", "auto").
default (any DSL/JSON value): Fallback written when no match is found.
join (string): Join multiple matches into a single string before coercing and writing.
allow_empty (bool, default false): Passed via InsertOptions when writing fields into dict.
Behavior: Walks the current node’s subtree once in a single pre-order traversal, retiring each first=true field as soon as it matches, and writes all extracted fields directly into dict (without modifying values).
Caveats: For ElementExists and AttributeExists, writes native JSON booleans (true/false) unless cast/as/to is explicitly set.
Caveats: Does not decode HTML entities like & (those are already decoded by libxml2 when extracting text/attr). Note url_decode does not convert + to space (unlike query_param).
Example: $("script") { text | unescape(url_decode=false) -> "raw" }
String mode (from, to="", first_only=false): Replaces all occurrences of from with to in each string by default (first_only=false). Pass first_only=true to replace only the first occurrence. No-op if from is "".
Mapping mode (mapping or {"old": "new", ...} / JSON string): Simultaneous single-pass Aho-Corasick replacement across all keys in mapping. Overlapping matches resolve by leftmost-longest.
Examples:
$("span") { text | replace(",", "") -> "clean_num" }
Behavior: Extracts a byte-indexed substring from each string in values.
start_pos (int, required): Supports negative indices (counts from end of string; clamped to 0 if -start_pos >= len).
length (int | null, default null): When null, takes to end of string. When > 0, takes up to length bytes. When == 0, clears the string. When < 0, trims abs(length) bytes from the end of the string (Python-style slice end).
Caveat: Operates on raw UTF-8 bytes, not Unicode codepoints.
Example: $("span.sku") { text | substring(4, -1) -> "sku_core" }
strip_comments(multiline=true, single_line=true)
Behavior: Strips /* ... */ (multiline=true) and/or // ... (single_line=true) comments from each value while respecting quoted strings.
Example: $("script") { text | strip_comments -> "clean_js" }
strip_tags()
Behavior: Strips <...> HTML/XML tags from each string in values, respecting quoted attributes inside tags.
Example: $("h1") { text | hash("sha256") -> "title_hash" }
slugify(separator="-", max_len=null)
Behavior: Lowercases ASCII letters, keeps [a-z0-9], replaces runs of other bytes with separator, strips leading/trailing separator, and optionally truncates to max_len (without leaving a trailing separator).
Caveat: Non-ASCII characters are treated as separators; pair with strip_accents() first for accented Latin text!
Caveat: Unknown entities and invalid codepoints (0, surrogates, > 0x10FFFF) are preserved literally.
Example: $("script") { text | unescape_html -> "decoded" }
parse_srcset(mode="largest")
Parameters:
mode (string, default "largest"): "largest" (or "best"), "smallest", or "all" (case-insensitive; unknown value throws std::invalid_argument).
Behavior: Parses HTML srcset attributes (url 2x, url 1080w, or bare url weighted as 1.0) and replaces values with the selected candidate URL(s). Drops items with no valid candidates.
Behavior: Runs a case-insensitive RE2 scan for url(...) declarations (double-quoted, single-quoted, or unquoted) across every string in values and replaces values with all extracted non-empty URLs.
URL steps process values (and dict for query_params) via libxml2’s RFC 3986 URI parser (xmlBuildURI, xmlParseURI, xmlSaveUri). query_params, strip_query, and filter_urls also include fallbacks for URLs with unencoded [ or ] in query strings.
Step
Parameters & Defaults
Aliases
Notes
resolve_url
(base_url)
url_join
Resolves relative URLs against base_url
url_part
(part)
—
Extracts scheme, host, port, path, query, or fragment
query_param
(name, default_val="")
—
Extracts & URL-decodes query param (+ → space)
query_params
(mapping, default_val="")
—
Multi-param query extraction into dict, clears values
strip_query
(keep_params=[], drop_params=[])
—
Strips all, non-whitelisted, or blacklisted query params (supports * globs)
Behavior: Replaces each URL in values with the requested component ("scheme", "host", "port", "path", "query", "fragment", case-insensitive). Clears invalid URLs or missing parts to "". Unknown part throws at parse time.
Behavior: Extracts the first query parameter matching name (after URL-decoding keys and values, with + → space). Replaces the value with default_val if the URL has no query or name is absent.
mapping (list<string> | string | object, required): Either a list ["id", "page"] (writes to dict["id"], dict["page"]) or an object {"utm_source": "meta.source"} mapping query parameter names to dot-path target keys.
default_val (string, default ""): Fallback written for missing parameters when default_val != "".
Behavior: Parses the query string of each URL in values once (URL-decoding keys/values with + → space; tolerating unencoded [/]), inserts extracted parameters into dict, and clears values (wrap in tee { ... } if you still need the URL afterwards).
When flags is null or "" (the default), RE2 runs case-sensitive.
Supported flags: "icase" or "i" (case-insensitive), "dotall" or "s" (. matches \n), "multiline" or "m" (^/$ match line boundaries). Full flag words ("icase", "dotall", "multiline") are consumed before single-letter flags (i/s/m), so "multiline" does not trigger icase, and short forms like "im" combine cleanly.
Invalid regex syntax throws std::invalid_argument at parse time.
regex_replace(pattern, replacement, flags=null) / sub
Behavior: Runs RE2::GlobalReplace on every string in values. Supports RE2 backreferences \1, \2, etc. in replacement.
Example: $(".price") { text | sub("[^0-9.]", "") -> "price" }
Behavior: Repeatedly runs unanchored non-overlapping RE2::Match across every string in values and replaces values with all extracted matches:
group_index == 0: emits non-empty captures 0..N per match.
group_index < 0: emits non-empty captures abs(group_index)..N per match.
group_index > 0: emits capturing group group_index per match (or "" if optional group didn’t participate).
Caveat: Advances cursor by 1 byte on zero-length matches to avoid infinite loops.
Example: $("p.tags") { text | regex_find_all("#([a-z0-9_]+)", 1) -> "hashtags" }
regex_groups(pattern, flags=null, prefix="")
Parameters:
pattern (string, required): RE2 regex containing named capturing groups (?P<name>...).
flags (string | null, default null): RE2 flags.
prefix (string, default ""): Prefix prepended to each named group when writing to dict.
Behavior: Matches pattern once per item in values, inserts each non-empty named capture into dict[prefix + name], and clears values (wrap in tee { ... } if you need values afterwards).
Example: $(".dim") { text | regex_groups("(?P<w>\\d+)x(?P<h>\\d+)", prefix="size_") }
filter(patterns)
Behavior: Multi-pattern literal filter using two compiled Aho-Corasick DFAs.
patterns (list<string> or string, required, non-empty):
"+foo" or "foo" → include pattern (value must contain at least one include pattern, if any includes exist).
"-bar" → exclude pattern (value is dropped if it contains any exclude pattern).
Caveats: Empty list throws. Empty string "" or bare "+"/"-" entries are ignored.
sort: Lexicographical std::sort by default; when numeric=true, uses std::stable_sort parsing trimmed numbers via std::from_chars (valid numbers sort before non-numeric strings).
Behavior: First erases all items containing only whitespace ("", " ", etc.) from values, then sets [default_value] if values.empty().
Example: $(".badge") { text | ?? "none" -> "badge" }
JS / JSON Block Digger
Step
Parameters & Defaults
Aliases
Mutates
js_block
(prefix="")
extract_js_block
Replaces values
js_blocks
(prefixes, aliases=null)
extract_js_blocks
Writes to dict, clears values
parse_js
(objname, simplify=true)
—
Writes to dict, clears values
js_block(prefix="") / extract_js_block
Behavior: For each string in values, searches after prefix (if non-empty) for the first {, [, or ( outside comments/strings and extracts the balanced block. Drops items where no balanced block is found.
Example: $("script#state") { text | js_block("window.__STATE__ =") | parse_js("state") }
List or string: each entry searches for entry and stores under entry as dot-path. Entries ending in "*" (length > 1, e.g. "varObj_*") search for "varObj_" and store under "varObj" (stripping * and trailing _).
Object {prefix: target_key}: searches for prefix and stores under target_key.
aliases (object | null, default null): Optional extra {prefix: target_key} mappings merged into the search list.
Behavior: For each string in values and each (prefix, target_key) entry, extracts the balanced block after prefix, parses it via digger::parse_object(..., simplify=true), inserts into dict at dot-path target_key (InsertMode::Merge), and clears values.
Example: $("script") { text | js_blocks(["app.config", "varObj_*"], aliases={"window.__USER__": "user"}) }
parse_js(objname, simplify=true)
Behavior: Joins values with \n, clears values, and parses with digger::parse_object(combined, simplify).
objname (string, required): Target dot-path in dict. If "", merges into dict root; otherwise inserts under objname.
Example: $("script") { text | js_block("cfg =") | parse_js("cfg") }
Dictionary, Typed Casting, JSON/CSV & Query Steps
Dictionary and JSON transformation steps (cast_keys through json_schema) run immediately on local dict when inside { ... } or .( ... ), or once on the accumulated dest document when placed at top level or inside finalize { ... }.
Behavior: Filters values to non-whitespace items, coerces each according to type, writes a scalar (1 item) or array (2+ items) to dict at dot-path name, and clears values.
Unparseable values for "int"/"float"/"number"/"bool" coerce to null (which is still written if it’s the sole value, or inside an array).
"bool" recognizes "true", "1", "yes", "y", "on", "in stock", "available" vs "false", "0", "no", "n", "off", "out of stock", "unavailable" (case-insensitive).
"auto" only converts "true", "false", "null", and numbers; otherwise keeps string.
Example: $(".qty") { text | set("quantity", type="int") }
append_to(key, allow_empty=false)
Behavior: Appends non-empty items (or all items if allow_empty=true) from values into an array at dict[key] using InsertMode::AppendToList, and clears values.
Behavior: Extracts the first numeric token from each string in values, stripping currency symbols/text and thousands, converting decimal to ., and supporting accounting parentheses ($12.50) → "-12.50".
compact (bool, default false): When true, expands K (1e3), M (1e6), B (1e9), T (1e12) suffixes (case-insensitive, not followed by another letter)—e.g., "1.2M" → "1200000".
If key == "": replaces values with the normalized numeric strings.
If key != "": writes native JSON numbers to dict[key] and clears values.
Example: $(".views") { text | to_number(key="views", compact=true) }
parse_duration(key="", unit="seconds")
Parameters:
key (string, default ""): Target dot-path in dict.
unit (string, default "seconds"): Output unit—"seconds" ("sec", "s"), "ms" ("millisecond", "milliseconds"), or "minutes" ("min", "m"). Unknown unit throws std::invalid_argument.
Behavior: Parses ISO-8601 (PT1H5M20S, P2DT3H), colon (MM:SS, HH:MM:SS with optional fractional seconds), and prose ("1h 5m 20s", "12 min 30 sec", "2 hours") durations, dropping unparseable items.
If key == "": replaces values with formatted numeric strings.
If key != "": writes native JSON ints/floats to dict[key] and clears values.
Example: $(".duration") { text | parse_duration(key="duration_sec", unit="seconds") }
Behavior: Coerces each string in values. Unparseable items are dropped unless default_val is non-null.
If key == "": replaces values with stringified coerced values.
If key != "": writes native JSON ints/floats/booleans to dict[key] and clears values.
Example: $(".stock") { text | to_bool(key="in_stock", default_val=false) }
cast_keys(schema)
Behavior: Traverses arrays and coerces matching string fields (or string elements of array fields) matching keys in schema ({key: "int"|"float"|"number"|"bool"|"auto"}). Keys in schema match immediate object property names; dot-separated paths (e.g., "parent.child") are not supported.
Behavior: Zips two parallel arrays input[keys_key] and input[values_key] (up to min(len1, len2)) into an object. If target_key == "", merges pairs into the active object; otherwise writes to out[target_key]. No-op if either key is missing or not an array.
mapping (object, required): {target_key: [source_path1, source_path2, ...]} (each value may be a list or single string dot-path).
drop_sources (bool, default true): Removes single-segment (top-level) source keys from the output object unless they also appear as a target_key.
Behavior: For each target_key, resolves candidate source_path dot-paths in order and writes the first non-null, non-empty value into target_key (overwriting with nested_path=true). Unlike pick_keys/omit_keys, source candidates support dot paths (e.g., "meta.title").
Behavior: Flattens nested objects by joining keys with _ (underscore, e.g., meta_author), and unwraps nested arrays by appending scalar values into arrays under the parent key.
Behavior: Recursively keeps only (pick_keys) or removes (omit_keys) object keys in the provided list across all nesting levels.
NOTE
pick_keys and omit_keys match exact property names (key), not dot-separated paths ("parent.child"). To omit a nested property such as @context inside json_ld, specify omit_keys(["@context"]) rather than omit_keys(["json_ld.@context"]).
Example: omit_keys(["@context", "raw_html"])
rename_keys(pairs)
Behavior: Recursively renames object keys across all nesting levels matching exact property names (pairs may be an object {old: new} or an even-length list ["old1", "new1", "old2", "new2"]; odd-length list throws). Dot-separated paths are not supported.
Example: rename_keys({"title": "heading"})
merge_keys(source_keys, target_key)
Behavior: Collects values from each key in source_keys on the root object (flattening arrays, skipping null), erases source_keys, and stores the combined array under target_key (if non-empty). source_keys must be top-level keys in the object (dot-separated paths are not supported).
Behavior: Recursively sorts JSON array elements using total JSON type ordering (null < bool < number < string < array < object). Object keys are already maintained in ascending alphabetical order by jsoncons::json.
Example: sort_array(ascending=true)
deduplicate()
Behavior: Recursively removes duplicate elements from JSON arrays using canonical JSON serialization (canonical_json_key).
Example: deduplicate()
jmespath(expr) & jsonpath(expr)
Behavior: Transforms the JSON document using a JMESPath expression or queries it using a JSONPath expression (jsoncons). Invalid expressions throw at runtime.
Behavior: Decodes CSV in values into dict (array of objects if assume_header=true, array of arrays if false) or encodes dict/dict[source_key] into CSV in values.
Example: $("pre.csv") { text | csv_parse("rows", delimiter=";") }
Behavior: Compiles and evaluates an XPath 3.1 expr via lxml2-query (XPathParser::Create / node.EvaluateXPath) relative to the current Node (available when built with -DXSEL_USE_XPATH3=ON, enabled by default).
Nodes: extracts attr (if non-empty, on element nodes) or stringValue().
Atomic items: appends asString().
Arrays: recursively flattens array members and appends their extracted values.
Caveats:
Invalid XPath 3.1 syntax throws at parse/construction time.
Map or function items throw lxml2::XPathTypeException (FOTY0014).
Behavior: Extracts the current <table> (or first descendant <table>) into a JSON array of row objects (header=true, deduplicating header names with _2, _3, … and col_N for empty headers) or row arrays (header=false). Supports colspan (up to 64; spanned cells get "").
normalize_headers=true: lowercases and replaces non-alphanumeric runs with _.
If key != "": writes native JSON array to dict[key] and clears values.
If key == "": pushes serialized JSON string into values.
Behavior: Searches the current node for <title>, <link rel="canonical" href="...">, <meta name|property|http-equiv="..." content="..."> (first occurrence wins per key), and <script type="application/ld+json"> (parsed into json_ld array; malformed JSON-LD blocks are skipped silently).
index_json_ld (bool, default false): When true (and include_json_ld=true), recursively indexes JSON-LD objects and @graph entries by @type under json_ld_by_type (a single object for one match, or an array for multiple).
Writes into dict[key] (or directly into dict root if key == "").
Behavior: Parses each trimmed non-empty string in values via absl::Time (using fmt if provided, or auto-detecting 15 common ISO/RFC/slash/month-name formats). When fmt == "" and auto-formats fail, falls back to relative expressions ("just now", "now", "today", "yesterday", "tomorrow", "last/next <unit>", "<N|a|an> <unit> ago", "in <N|a|an> <unit>"). Unparseable strings are dropped.
output: "iso" (%Y-%m-%dT%H:%M:%SZ for UTC, %Y-%m-%dT%H:%M:%S%Ez otherwise), "date" (%Y-%m-%d), "unix" (integer seconds), "unix_ms" (integer milliseconds), or any custom absl::FormatTime format string.
now (string, default ""): Optional anchor timestamp (auto-parsed in tz) used for relative expressions instead of absl::Now().
If key == "": replaces values with formatted strings.
If key != "": writes native ints/strings to dict[key] (when at least one date parsed) and clears values.
Caveat: Unknown tz or invalid now throws std::invalid_argument.
Example: $("time") { text | parse_date(output="date", now="2026-11-20T12:00:00Z", key="posted_date") }
unicode_normalize(form="NFC") & strip_accents()
Behavior:
unicode_normalize: Normalizes UTF-8 strings in values to NFC, NFD, NFKC, or NFKD (case-insensitive). Unknown form throws.
strip_accents: Decomposes and strips combining marks (UTF8PROC_DECOMPOSE | UTF8PROC_STRIPMARK) — e.g. "Café" → "Cafe".
Behavior: Prints values (with indices and quoted strings), and optionally dict (print_dict=true) and node.Text() / node.OwnText() (print_node=true) to stderr. Does not modify values or dict.
Example: $(".price") { text | debug("raw_price", print_dict=true) | trim -> "price" }
Control Flow, Branching, Slots & Composition
Construct / Step
Syntax / Parameters
Aliases
Scope / Behavior
save / restore
save(name) / restore(name)
—
Save/recall values in per-node ExecutionContext slots
Conditional block if any item in values matches RE2 pattern
skip_if_exists
skip_if_exists(selector)
—
Drops current item before merge if selector matches inside Node
skip_if_empty
skip_if_empty()
—
Drops current item before merge if values has no non-whitespace items
abort_if_exists
abort_if_exists(selector, key="", reason="")
—
Optionally sets dict[key], then aborts remaining extractors
finalize
finalize { ... }
—
Scraper-level post-processing block (always runs once at end)
pipe / use
pipe name = { ... } / use(name)
—
Defines and splices reusable step sequences
include
include(scraper_name)
—
Appends extractors and finalize steps from another scraper
save(name) & restore(name)
Behavior: save(name) snapshots values into ctx.slots[name] for the current node; restore(name) restores values from ctx.slots[name] (or clears values if name was never saved).
Caveats:
Slots belong to the current Extractor match’s ExecutionContext; they are shared with nested tee, when_*, and unless_exists blocks on the same node, but not across different matched nodes or each(...) sub-extractors.
Calling SaveValuesStep directly in C++ without an ExecutionContext throws std::runtime_error.
Behavior: Clones values into local_values and executes the steps inside { ... } against (node, local_values, dict, ctx). Dict/JSON transforms inside tee run immediately against dict. When the block exits, outer values remains unmodified.
Caveats: Shares dict and ctx (save/restore, skip_item, abort_scraper) with the outer node pass.
selector (string, required): CSS selector evaluated relative to the current Node (pass "" to target the current Node itself).
key (string, default ""): Optional dot-path in dict under which matched sub-items are merged.
Behavior: Runs a nested Extractor inside the current Node, supporting arbitrary nesting, overlapping-key array grouping, and @key / @value collapsing. (Writing select(sel, key) { ... } or $(sel, key) { ... } directly inside { ... } is syntactic sugar for each(sel, key) { ... }.)
Caveats: Does not read or modify the outer values vector. If abort_if_exists triggers inside each, ctx.abort_scraper propagates to abort the outer scraper too.
when_exists(selector) / unless_exists(selector): Runs { ... } on the shared (node, values, dict, ctx) if selector matches (or does not match, for unless_exists) any node inside the current Node.
when_match(pattern, negate=false, flags=null): Runs { ... } if any string in values matches RE2 pattern (RE2::PartialMatch; inverted when negate=true). Uses the same RE2 flags rules as Regex, Aho-Corasick & Filtering (null/"" = case-sensitive).
Caveats: Dict/JSON transforms placed inside these blocks execute immediately on dict when the condition passes.
skip_if_exists(selector): Sets ctx.skip_item = true if selector matches inside the current Node, discarding the current item before merging into dest.
skip_if_empty(): Sets ctx.skip_item = true if values contains no non-whitespace strings.
abort_if_exists(selector, key="", reason=""): If selector matches inside the current Node, optionally writes reason (or true when reason == "") to dict[key] (using Overwrite, nested_path=true) if key != "", sets ctx.abort_scraper = true (leaving the current item to merge), and stops all remaining extractors.
Caveats: Even when abort_if_exists fires, finalize { ... } still executes afterwards.
Behavior: Attaches post-processing steps to the scraper that execute once after all extractors finish (and after the first preprocess_key_value pass), even if preceding extractors matched 0 nodes or abort_if_exists aborted early. Every step inside finalize (including dict/JSON transforms) runs immediately with root_node, an empty values vector, and dest as dict. Top-level dict/JSON transforms placed outside { ... } blocks execute in this same pass. Runs preprocess_key_value again upon completion.
pipe <name> = { ... } (top-level declaration; =, :, :=, or space accepted before {): Compiles a reusable step sequence. use(<name>) splices those steps into the current chain at parse time (unknown <name> throws).
include(<scraper_name>): Appends all extractors and finalize steps from a previously declared scraper into the current scraper (unknown <scraper_name> throws).