selectolax-schema
Schema-driven HTML extractor powered by selectolax's maintained Lexbor backend. Define extraction specs in Python (with full IDE type hints) or YAML, and get structured JSON out.
The field model and observable API mirror scrapling-schema 1.1.3; the Python
package and CLI are named selectolax_schema and selectolax-schema.
Install
pip install selectolax-schema
Requirements
- Python >= 3.10
- selectolax >= 0.3.0
- PyYAML >= 6.0
Python API
Python type spec (recommended)
from selectolax_schema import Schema, Field, Options, Clear, RegexSub
spec = Schema(
options=Options(clear=Clear(remove_tags=["script", "style"])),
fields={
"products": Field(
css=".product",
type="array<object>",
fields={
"sku": Field(css="SELF", type="string", attr="data-sku"),
"name": Field(css=".name", type="string"),
"url": Field(css="a.link", type="string", attr="href"),
"price": Field(css=".price", type="number", transform=[
RegexSub(pattern=r"[^0-9.]+"),
]),
"tags": Field(css=".tags li", type="array<string>"),
},
)
},
)
result = spec.extract(html)
json_schema = spec.json_schema(title="Products")
Boolean fields (type: "boolean")
Boolean output is derived from type, not a transform. The extractor coerces common truthy/falsey values:
- truthy:
"true","t","yes","y","on","1"(case-insensitive, surrounding whitespace ignored) - falsey:
"false","f","no","n","off","0" - numbers:
1→True,0→False(other numbers becomeNone)
Python example:
from selectolax_schema import Schema, Field
html = "<span class='in-stock'> yes </span>"
spec = Schema(fields={"in_stock": Field(css=".in-stock", type="boolean")})
data = spec.extract(html)
assert data["in_stock"] is True
If you want invalid/missing values to fail fast, set nullable=False:
from selectolax_schema import Schema, Field, ValidationError
html = "<span class='in-stock'> maybe </span>"
spec = Schema(fields={"in_stock": Field(css=".in-stock", type="boolean", nullable=False)})
try:
spec.extract(html)
except ValidationError:
pass
YAML spec
options:
clear:
remove_tags: ["script", "style"]
fields:
products:
css: ".product"
type: "array<object>"
fields:
sku:
css: "SELF"
type: "string"
attr: "data-sku"
name:
css: ".name"
type: "string"
price:
css: ".price"
type: "number"
transform:
- regex_sub: { pattern: "[^0-9.]+", repl: "" }
in_stock:
css: ".in-stock"
type: "boolean"
from selectolax_schema import extract_from_yaml
result = extract_from_yaml(html, yaml_spec)
CLI
selectolax-schema --version
selectolax-schema --spec spec.yml --html-file page.html
selectolax-schema --spec spec.yml --schema
The installed package version is also available in Python:
from selectolax_schema import __version__
Field reference
| param | type | description |
|---|---|---|
css |
str |
CSS selector. Use "SELF" to select the context node itself |
attr |
str |
Extract an attribute value (or special "innerHTML") |
type |
str |
Output type: `"string" |
nullable |
bool |
If false, missing values raise ValidationError |
defaultValue |
any |
Fallback value used when the extracted value is empty |
fields |
dict |
Nested fields (for object / array<object>) |
transform |
list |
Transform pipeline (see below) |
postprocess |
callable |
Receives the field's fully extracted value and returns its output value (Python API only) |
callback |
callable |
Deprecated compatibility alias for postprocess; emits DeprecationWarning |
outputSchema |
dict |
Override JSON Schema for this field (useful when postprocess changes the output type/shape) |
required |
bool |
Raise ValidationError if value is empty |
Notes:
typeis required for every field.- Arrays must use
type: "array<...>"(noitems:and nolist:). attrsupports special values:"innerHTML": extract HTML string from the selected node."ownText": extract direct text for the selected node (excludes descendant text).
Transform reference
| transform | shorthand | description |
|---|---|---|
RegexSub(pattern, repl) |
— | Regex substitution |
Split(delimiter) |
— | Split string into array items (requires type:"array<...>") |
Notes:
- String outputs are stripped automatically (no transform needed).
- Use field-level
defaultValuefor fallbacks (defaults are not supported inside transforms).
When to use transform vs postprocess
Both are meant for post-processing, but they work at different levels and have different ergonomics.
Use transform for value-centric pipelines
Good fit when you want a predictable, reusable pipeline on a single extracted value (e.g., regex cleanup, split).
Order of operations (scalar fields):
- Extract raw string
- Apply
transformpipeline - Apply
typecoercion (number/integer/boolean) - Apply
postprocess(if any) - Check
required
Example: remove currency symbols before coercing to number:
from selectolax_schema import Schema, Field, RegexSub
spec = Schema(
fields={
"price": Field(
css=".price",
type="number",
transform=[RegexSub(pattern=r"[^0-9.]+", repl="")],
)
}
)
data = spec.extract(html)
Use postprocess for whole-field logic (filtering, sorting, aggregation)
postprocess receives the fully extracted value for the field and returns its output value:
- scalar field → the scalar value (
str|int|float|bool|None) array<...>field → the whole listobjectfield → the whole dict
This is a better fit for list-level operations or aggregations.
callback remains available as a deprecated compatibility alias with the same behavior.
Using it during extraction or JSON Schema generation emits a DeprecationWarning
that points to the calling code and recommends postprocess. It will be removed in
a future version; no removal version has been scheduled. Replace callback=my_fn
with postprocess=my_fn in typed fields, or rename the key in Python dict specs.
Do not set both names to non-None values on the same field: extraction and JSON
Schema generation raise ExtractError. None disables the corresponding hook.
Python normally hides library deprecation warnings. Run python -Wd your_script.py
to display them, or configure your test runner to treat deprecation warnings as errors.
When postprocess changes the output type/shape
postprocess is an arbitrary Python function, so the library cannot reliably infer a JSON Schema for its return value.
If your function changes the type/shape (e.g., list → object, object → string), set outputSchema on the field to
keep spec.json_schema() in sync with the actual output.
Example: filter a list of objects (keep only items you care about):
from selectolax_schema.types import Schema, Field
def keep_only_a(items: list[dict]) -> list[dict]:
return [item for item in items if "A" in item["name"]]
spec = Schema(
fields={
"products": Field(
css=".item",
type="array<object>",
postprocess=keep_only_a,
fields={
"name": Field(css=".name", type="string"),
},
)
}
)
data = spec.extract(html)
array<object> special case: transform is per-item
For type: "array<object>", transform is applied to each extracted object (each list element).
If a transform returns None, the item is dropped from the list.
from selectolax_schema import extract
def drop_product_a(item: dict) -> dict | None:
return None if item.get("name") == "Product A" else item
spec = {
"fields": {
"products": {
"css": ".item",
"type": "array<object>",
"transform": [drop_product_a],
"fields": {"name": {"css": ".name", "type": "string"}},
}
}
}
data = extract(html, spec)
YAML note
YAML specs support only the built-in transform steps (e.g., regex_sub, split).
Python callables (transform: [my_fn] / postprocess: my_fn, including the deprecated callback alias) are only supported via the Python API (typed Schema/Field or a Python dict spec), not via YAML text.
Memory lifetime
The parser and DOM are local to each extraction. Text collection uses an iterative traversal, so deeply nested HTML does not consume Python recursion depth or create recursive closure cycles.
After the DOM is built, extract() releases its reference to the preprocessed
HTML string before evaluating fields.
Field evaluation releases its DOM references on both normal return and failure. This also covers postprocessors and transforms that catch an error, retain the exception, and return successfully.
When extract() raises, it clears its finished internal traceback frames to
release the DOM and temporary values. All extraction entry points drop their own
HTML input references when they finish. Exception identity, messages, traceback
locations, and user hook locals are preserved. Locals from cleared library
frames are therefore unavailable when inspecting a saved traceback. Callers and
hooks can still retain their own inputs or values.
Testing
Install the dev dependencies (in a virtualenv) and run the test suite:
python -m pip install -e ".[dev]"
python -m pytest
Run a single test file:
python -m pytest tests/test_extractor.py
License
Metadata
Release files for selectolax-schema 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| selectolax_schema-0.2.0.tar.gz | 32.2 kB | With provenance | Details for selectolax_schema-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| selectolax_schema-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for selectolax_schema-0.2.0-py3-none-any.whl |
Total release size: 49.7 kB
Release files / selectolax_schema-0.2.0.tar.gz
| Download URL | selectolax_schema-0.2.0.tar.gz |
|---|---|
| Size | 32.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6984910b79cdba04155e52a0503cbb19cee8857d076d7ae75f37c42c4c5a395d
|
|
BLAKE2b-256 checksum How to use checksums |
329ceaf6d1e13bbcfc891f98a2671d56b946a19e3c6d0b10ddd70ee1953bfe18
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.
Transparency logRelease files / selectolax_schema-0.2.0-py3-none-any.whl
| Download URL | selectolax_schema-0.2.0-py3-none-any.whl |
|---|---|
| Size | 17.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2b507216afef1412a22ad9fda77b6c92e46188a42b69d2bf718eaa092ce78610
|
|
BLAKE2b-256 checksum How to use checksums |
cbba3bb09e26261749096ffe5653530c53c0601eece0a3c0b65e988fb93ed171
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.
Transparency logSecurity for selectolax-schema 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for selectolax_schema-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.