API reference
extract()
Extract structured data from any web page
15 min read
Extracting from many pages? Pass an extract_schema to client.crawl() and it will extract structured data from every page on the site in a single call — no manual iteration needed.
Endpoint
POST /api/v1/organizations/{org_id}/kolektr/extract
The SDKs call it as kolektr.page().
Description
Extract structured data from a web page with CSS selectors. Pass a fetch_artifact_id from a previous fetch() call to skip re-fetching the page.
Request body
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| url | string | Yes | — | Target page URL |
| schema_spec | object | No | null | The fields to extract (below) |
| fetch_artifact_id | string | No | null | Reuse HTML from a prior fetch |
| session_artifact_id | string | No | null | Authenticated session from Fetchyr, such as a login session |
| api_map_artifact_id | string | No | null | API map from a prior discovery |
| level | string | No | null | level1, level2, or null for automatic. The response's level and level_reason say which ran and why. In automatic mode a Level 1 run that falls short moves to Level 2 once (below), which uses more data; level: "level1" avoids that |
| options | object | No | null | Extra options passed to the extractor. entity_type (such as "products") names what the page lists and, when level is left out, asks for AI extraction (Level 2); schema_spec.entity_type is the same option |
| include_resources | array of strings | No | [] | The page's extras to load when a browser renders it: any of images, media, fonts, stylesheets, tracking. Left out or empty: none are loaded, to save data. Also on …/kolektr/extract/html. See extras |
| robots_acknowledged_hosts | array of strings | No | null | Hosts whose robots.txt stop you acknowledge, for this request only: the host of the 409 that stopped it. Recorded. See robots.txt |
schema_spec
{
"item_selector": "article.product_pod",
"fields": [
{ "name": "title", "selector": "h3 a", "attribute": "title" },
{ "name": "price", "selector": "p.price_color" }
]
}
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| fields | array | [] | The fields to extract. Each has a name, an optional CSS selector (without one the field is read from the page's structured data: below), an optional attribute to read instead of the text, and a type (default text; types) |
| item_selector | string | null | CSS selector for the repeated item on a list page: one record per matching element (below) |
| pagination, max_pages | boolean, integer | false, 1 (at most 100) | Follow the page's next-page links and extract up to max_pages pages, the first included (below). Only when KLOAKD fetches the page itself |
| entity_type | string | null | What the page lists, such as "products". The same as options.entity_type, which it fills in: when level is left out, naming one asks for AI extraction (Level 2); a level you name still wins. Send it in one place, or the same value in both (a different value answers 422 entity_type_conflict; an empty one, 422). Only when KLOAKD fetches the page: kolektr/extract/html answers 422 entity_type_needs_fetch |
One record per item (item_selector)
A list page — products, search results, articles — repeats one element per item. Give that element's CSS selector as item_selector and each match becomes one record, with every field's selector read inside that element:
- the first match gives the field's value (its text, or the
attributeyou name); type: "list"gives every match inside the item, as a list;- a field with no match in an item is
nullin that record; - a field with no
selectoris read from the item element itself (for example an attribute on it).
On books.toscrape.com, the request
{
"url": "https://books.toscrape.com/",
"schema_spec": {
"item_selector": "article.product_pod",
"fields": [
{ "name": "title", "selector": "h3 a", "attribute": "title" },
{ "name": "price", "selector": "p.price_color" }
]
}
}
answers 20 records, one per book (total_records: 20):
{
"records": [
{ "title": "A Light in the Attic", "price": "£51.77" },
{ "title": "Tipping the Velvet", "price": "£53.74" }
],
"total_records": 20
}
(two of the 20 shown). When nothing matches item_selector, the extraction gives 0 records. An empty or invalid CSS item_selector, or an item_selector with no fields, is refused with 422.
Without item_selector each field's selector runs against the whole page and the page is one record: a field matching many elements gives its first match, or every match as a list with type: "list" or an attribute. KLOAKD does not guess rows from those lists, so a list page read without item_selector comes back as one record of parallel lists.
The whole field spec (selector, attribute, type) is applied with or
without item_selector: when KLOAKD fetches the page itself (the default),
with a fetch_artifact_id, and in
kolektr/extract/html. Without
item_selector, a field with an attribute gives that attribute of every
match, as a list. A Level 2 extraction (level: "level2" or
options.javascript_enabled) that renders the page in a browser applies
them to the page it rendered; when item_selector matches nothing there,
Level 2's own records are kept, typed. When the run is made by the
strategy engine (method: "level2_se"), the same applies to the page the
crawler sends back; if no page comes back, only type is applied. Level 2 does not read fields
without a selector from the page's structured data.
Fields without a selector
A field given by name only (no selector, no item_selector) is read from what the page says about itself, in this order:
- its JSON-LD, microdata and RDFa, by the field's name or an alias:
priceisoffers.price,ratingisaggregateRating.ratingValue,brandisbrand.name; - its meta tags:
og:,product:,article:,twitter:, andnameoritempropmeta tags; - for
title,heading,descriptionandurl: the page's<title>, first<h1>, meta description and canonical link.
Names are compared without case, _ or -. A name the page gives nowhere is null; nothing is guessed. A request whose fields are all named this way answers one record with just those fields.
{
"url": "https://shop.example/product/42",
"level": "level1",
"schema_spec": {
"fields": [
{ "name": "name" },
{ "name": "price", "type": "number" }
]
}
}
This reading is done when the page is read at Level 1 (KLOAKD's own fetch), from a fetch_artifact_id, and in kolektr/extract/html. In automatic mode (level left out) a request whose fields all lack a selector runs at Level 2, which does not read structured data this way: name level: "level1" to have it read. Fields with and without selectors can be mixed in one request.
Field types
type converts each value: text (the default; a number becomes a string), number (also float, decimal: "$1,299.00" is 1299.0, "1.299,50 €" is 1299.5), integer (int), boolean (bool), url (made absolute against the page), list (every match), and date or datetime, which are kept as the page gives them. A value that does not read as its type is null.
Next pages (pagination)
With pagination: true and max_pages above 1, the extraction follows the page's next-page link and extracts each next page with the same schema, at the same level, until it has read max_pages pages (the first included). The next page is a link with rel="next", a link reading Next, ›, » or → (or with that aria-label), or the next number in the page's pagination block. Only links on the same host, over http or https, are followed.
{
"url": "https://books.toscrape.com/catalogue/page-1.html",
"schema_spec": {
"item_selector": "article.product_pod",
"fields": [{ "name": "title", "selector": "h3 a", "attribute": "title" }],
"pagination": true,
"max_pages": 3
}
}
reads pages 1 to 3: 60 records (20 a page) in page order, pages_scraped: 3.
- Each next page is checked against the site's robots.txt and KLOAKD's blocked domains before it is fetched; a page they do not allow ends the paging (the records already read are kept).
robots_acknowledged_hostscounts for the next pages too. - Paging also stops at a page with no next page, a next page already read, a page whose extraction fails (the records before it are kept), or a page with no records.
pages_scrapedis the number of pages extracted; the response does not say why paging stopped.- Load-more buttons and infinite scroll are not followed: such a list gives its first batch.
- Paging needs a page KLOAKD fetches: with
fetch_artifact_id,api_map_artifact_idorkolektr/extract/html,paginationwithmax_pagesabove 1 answers 422pagination_needs_fetch(Errors).
The SDKs also accept a shorthand, {"title": "css:h3 a"} (the css: prefix is optional), and convert it to fields; a full spec or a list of fields is sent as given.
Response
{
"success": true,
"url": "https://books.toscrape.com",
"method": "level1",
"records": [
{ "title": "Book A", "price": "$12.99" },
{ "title": "Book B", "price": "$8.50" }
],
"total_records": 2,
"pages_scraped": 1,
"artifact": { "artifact_id": "art-abc123", "type": "PARSED_SCHEMA" },
"job_id": "…",
"error": null,
"level": "level1",
"level_reason": "auto: …",
"auth_required": false,
"discovery_id": null,
"login_options": null
}
Response fields
| Field | Type | Description |
|-------|------|-------------|
| success | boolean | Whether extraction succeeded. Check it: a failed extraction is still HTTP 200 with the reason in error |
| url | string | The page URL |
| method | string | How the records were extracted: fetched_content_artifact (from a fetch_artifact_id; artifact when that artifact could not be read), api_map_artifact, level1, level2 (Level 2 in a browser), level2_se (Level 2 by the strategy engine), in_process_html (extract/html), or preflight_auth_detect (the page showed a login form, so nothing was extracted) |
| records | array | Extracted data records: one per item with item_selector, otherwise one for the page; with pagination, those of every page in page order. All of them in one response |
| total_records | integer | Number of records |
| pages_scraped | integer | Pages extracted: 1, or with pagination the pages followed, the first included |
| artifact | object or null | Reusable artifact (artifact_id, type); the SDKs expose it as artifact_id |
| job_id | string or null | The extraction job's ID, when one ran |
| level | string or null | For a fresh scrape, the level it ran at: level1 or level2. null when the records came from an artifact |
| level_reason | string or null | Why that level: Level 1 requested, Level 2 requested, javascript_enabled requested, or, in automatic mode, auto: followed by what chose it, then ; moved to level2: … when Level 1 fell short and Level 2 ran (below) |
| auth_required | boolean | A login form was found instead of the content (checked only when you send no session_artifact_id). success is then true with no records and method: "preflight_auth_detect" |
| discovery_id | string or null | When auth_required is true: the auth-chain discovery started for the login |
| login_options | object or null | When auth_required is true: how to log in with your own account; the same object as on fetch() |
| error | string or null | Error message if failed |
When Level 1 falls short
In automatic mode (level left out) a request that runs at Level 1 moves to Level 2 once when the Level 1 run failed, or when fields were asked for and no record has a value for any of them. Level 2 extracts the page again, which uses more data. Its result is returned when it succeeds, with level: "level2" and a level_reason such as auto: …; moved to level2: Level 1 returned no value for the requested fields (price). When Level 2 fails too, Level 1's result is returned with level: "level1" and ; level2 failed (…), level1's result kept added to level_reason. A page robots.txt stopped is not tried again, and with pagination the next pages run at the level that answered the first.
A level you name never moves: send level: "level1" to keep an extraction at Level 1 and its data use at one fetch.
Examples
Each example reads the 20 books on the page as 20 records.
Python
from kloakd import Kloakd
client = Kloakd(api_key="sk-live-...", organization_id="your-org-id")
result = client.kolektr.page(
"https://books.toscrape.com/",
schema={
"item_selector": "article.product_pod",
"fields": [
{"name": "title", "selector": "h3 a", "attribute": "title"},
{"name": "price", "selector": "p.price_color"},
],
},
)
if not result.success:
print("Extraction failed:", result.error)
for record in result.records: # 20 records
print(record["title"], record["price"])
A full spec (a dict with a fields list) is sent as given, so this works with the Python SDK 0.5.0.
TypeScript
import { Kloakd } from 'kloakd-sdk';
const client = new Kloakd({
apiKey: 'sk-live-...',
organizationId: 'your-org-id',
});
// SDK 0.6.0 and later: itemSelector is sent as item_selector
const result = await client.kolektr.page('https://books.toscrape.com/', {
schema: {
itemSelector: 'article.product_pod',
fields: [
{ name: 'title', selector: 'h3 a', attribute: 'title' },
{ name: 'price', selector: 'p.price_color' },
],
},
});
console.log(result.totalRecords, result.records);
itemSelector needs the TypeScript SDK 0.6.0 or later; 0.5.0 drops it.
Go
client := kloakd.MustNew(kloakd.Config{
APIKey: "sk-live-...",
OrganizationID: "your-org-id",
})
result, _ := client.Kolektr.Extract(ctx, "https://books.toscrape.com/",
&kloakd.ExtractOptions{
SchemaSpec: map[string]interface{}{
"item_selector": "article.product_pod",
"fields": []map[string]string{
{"name": "title", "selector": "h3 a", "attribute": "title"},
{"name": "price", "selector": "p.price_color"},
},
},
})
for _, r := range result.Records { // 20 records
fmt.Println(r["title"], r["price"])
}
A SchemaSpec with a fields key is sent as given, so this works with the Go SDK 0.5.0; 0.6.0 adds ExtractOptions.ItemSelector (see the Go SDK).
cURL
curl -X POST https://api.kloakd.dev/api/v1/organizations/$ORG_ID/kolektr/extract \
-H "Authorization: Bearer sk-live-..." \
-H "Content-Type: application/json" \
-d '{"url": "https://books.toscrape.com/", "schema_spec": {"item_selector": "article.product_pod", "fields": [{"name": "title", "selector": "h3 a", "attribute": "title"}, {"name": "price", "selector": "p.price_color"}]}}'
Artifact chaining
Pass a fetch_artifact_id to skip re-fetching:
page = client.evadr.fetch("https://books.toscrape.com")
result = client.kolektr.page(
"https://books.toscrape.com",
schema={"title": "h3 a", "price": "p.price_color"},
fetch_artifact_id=page.artifact_id,
)
Long extractions: 202
An extraction that is still running after about 85 seconds answers 202 with a job_id and a poll_url (/api/v1/organizations/{org_id}/handoff/{job_id}). Poll it until status is completed (the response above is in result) or failed. The job is kept for one hour; after that the poll answers 404. The SDKs follow it for you; after a JobTimeoutError, resume with client.wait_for_handoff(job_id) / waitForHandoff(jobId). See Long fetches.
An extraction made while all of your plan's work slots are in use is queued, not refused. If it is still waiting after the 85 seconds, the 202 has reason: "queued_for_slot"; the job runs when a slot frees, and ends failed if none frees within 15 minutes.
robots.txt
An extraction reads the site's robots.txt before it fetches the page, as every
route does. When the file does not allow the page, or cannot be read, the API
answers 409 ROBOTS_DISALLOWED with the host, the reason and the rule,
and nothing is fetched. To extract anyway, send the same request again with
that host in robots_acknowledged_hosts; it counts for that request only and
is recorded. A 503 ROBOTS_CHECK_UNAVAILABLE (with reason: "exits_refused"
when every exit refused to connect to the site) is not a stop: there is nothing
to acknowledge; retry later. The details, the body of each answer and an
example are on the fetch page.
Errors
| Status | Error | When |
|--------|-------|------|
| 200 with success: false | — (not an HTTP error) | The extraction did not succeed: see error |
| 202 | — (not an error) | Still running at the limit: poll the job |
| 401 | AuthenticationError | Missing or invalid API key |
| 402 | PaymentRequiredError | The plan's last payment failed |
| 403 | NotEntitledError / ForbiddenError | Not in the plan (NotEntitledError), or another organisation's ID (ForbiddenError) |
| 409 | ApiError | ROBOTS_DISALLOWED: the site's robots.txt stopped the request; nothing was fetched. Acknowledge it with robots_acknowledged_hosts (robots.txt) |
| 422 | ApiError | The request body failed validation (for example a schema field without name, or an empty or invalid CSS item_selector, or item_selector with no fields). Also pagination_needs_fetch: pagination with max_pages above 1 together with fetch_artifact_id or api_map_artifact_id; the body is {"detail": {"error": "pagination_needs_fetch", "message": "…"}}. entity_type_conflict: schema_spec.entity_type and options.entity_type differ. entity_type_needs_fetch: schema_spec.entity_type on kolektr/extract/html |
| 429 | QuotaExceededError / RateLimitError | GB allocation used up (gb_exhausted), a request-rate limit where one applies, or queue_full: all of your work slots are in use and too many requests are already waiting (Retry-After: 30; Rate limits). An extraction over the limit is otherwise queued, not refused |
| 502 | UpstreamError | The request could not be run or handed to a job. Also a Level 2 extraction (level: "level2") whose browser fetch got no page: detail starts Extraction failed: Level 2 got no page from its browser fetch: and names why, in the words a Level 1 fetch uses (how the fetch ended and its last attempt's reason). In automatic mode Level 1's result is kept instead (above) |
| 503 | BillingUnavailableError | Usage could not be checked; retry after Retry-After |
| 503 | ApiError | ROBOTS_CHECK_UNAVAILABLE: KLOAKD could not check the site's robots.txt (reason: exits_refused: every exit refused to connect). Not a stop and nothing to acknowledge; retry later |
Learn more
- crawl() orchestrator — extract from an entire site in one call with
extract_schema - Kolektr module — advanced extraction options
- Pagination guide — next pages, crawl cursors and API offsets
- Batch extraction guide — crawl then extract pattern
