API Reference¶
Configuration¶
Load and create crawl components from TOML config files.
load_config
¶
Load configuration from a TOML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Path to the TOML config file |
required |
Returns:
| Type | Description |
|---|---|
WebsiteConfig
|
WebsiteConfig with parsed settings |
Supports config composition via extends:
extends = "base.toml" # Path relative to this config file
name = "mysite"
# ... child config overrides/extends base
Example config
name = "example"
start_urls = ["https://example.com/products"]
# Or load from file:
# start_urls = { file = "urls.txt" }
[extract]
type = "html"
id_field = "product_id" # Optional: field for item deduplication
[extract.items]
selector = ".product-card"
fields.title = "h2.title"
fields.price = { selector = ".price", parser = "parse_price" }
[extract.links]
pagination = ["a.next-page"]
items = [".product-card a"]
[policy]
max_retries = 3
max_requests = 100
[storage]
path = "data/example"
Source code in src/databrew/config/loader.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
create_components
¶
Create all crawl components from config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
WebsiteConfig
|
Parsed website config |
required |
fresh
|
bool
|
Force fresh crawl (re-add start URLs even if queue has pending) |
False
|
Returns:
| Type | Description |
|---|---|
CrawlComponents
|
CrawlComponents with all initialized components |
Resume behavior
- If queue has pending URLs and fresh=False: resume (don't re-add start_urls)
- If queue is empty or fresh=True: fresh start (add start_urls)
Source code in src/databrew/config/loader.py
WebsiteConfig
¶
Bases: BaseModel
Parsed website configuration.
Source code in src/databrew/config/loader.py
CrawlComponents
dataclass
¶
Orchestrator¶
Main crawl coordination and execution.
Orchestrator
¶
Coordinates fetching, extraction, and storage.
The orchestrator: 1. Pulls item URLs from the store queue 2. Fetches content concurrently 3. Extracts items and links 4. Saves items to the store (with dedup by item_id or URL) 5. Adds pagination links to in-memory set 6. Adds new item links to queue (if not already scraped) 7. Handles retry logic based on policy 8. Checks stopping conditions
Example:
store = StateStore("data/mysite/state.db", id_field="property_id")
store.add_item_url("https://example.com/listing")
orchestrator = Orchestrator(
store=store,
fetcher=HttpxFetcher(),
extractor=HtmlExtractor(config),
policy=CrawlPolicy(concurrency=10),
)
result = await orchestrator.run()
print(f"Extracted {result.stats.items_extracted} items")
store.export_jsonl("output.jsonl")
Source code in src/databrew/orchestrator.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
__init__
¶
__init__(store, fetcher, extractor, policy=None, middleware=None, on_item=None, on_url_complete=None, on_error=None, full_crawl=False)
Initialize the orchestrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
StateStore
|
Unified state store for URLs and items |
required |
fetcher
|
Fetcher
|
Fetcher for retrieving content |
required |
extractor
|
Extractor
|
Extractor for parsing content |
required |
policy
|
CrawlPolicy | None
|
Crawl policy (defaults to CrawlPolicy()) |
None
|
middleware
|
list[Middleware] | None
|
List of middleware to apply (in order) |
None
|
on_item
|
OnItemCallback | None
|
Callback for each extracted item (item, is_new) |
None
|
on_url_complete
|
OnUrlCallback | None
|
Callback when a URL is processed |
None
|
on_error
|
OnErrorCallback | None
|
Callback for errors (url, message) |
None
|
full_crawl
|
bool
|
Disable caught-up stopping, crawl all pagination |
False
|
Source code in src/databrew/orchestrator.py
run
async
¶
Run the crawl with concurrent fetching.
Processes URLs from the store until: - Queue is empty - Stopping condition is met - Error threshold exceeded
Returns:
| Type | Description |
|---|---|
CrawlResult
|
CrawlResult with stats and store reference |
Source code in src/databrew/orchestrator.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
CrawlPolicy
¶
Bases: StrictModel
All behavioral rules in one place.
This centralizes decisions about: - When to retry a failed request - When to stop crawling - When to checkpoint
Source code in src/databrew/core/policy.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
retry_delay
class-attribute
instance-attribute
¶
Initial delay between retries (seconds).
backoff_factor
class-attribute
instance-attribute
¶
Multiply delay by this factor after each retry.
max_retry_delay
class-attribute
instance-attribute
¶
Maximum delay between retries (seconds).
retryable_categories
class-attribute
instance-attribute
¶
Error categories that should be retried.
max_requests
class-attribute
instance-attribute
¶
Maximum requests to process (None = unlimited). Retries don't count.
max_consecutive_failures
class-attribute
instance-attribute
¶
Stop after this many consecutive failures.
max_error_rate
class-attribute
instance-attribute
¶
Stop if error rate exceeds this (0.0 to 1.0).
min_requests_for_error_rate
class-attribute
instance-attribute
¶
Minimum requests before error rate check applies.
stop_on_empty
class-attribute
instance-attribute
¶
Stop pagination when a page yields no items or links.
stop_on_caught_up
class-attribute
instance-attribute
¶
Stop globally when reaching already-scraped items.
Note: Per-branch stopping is now handled automatically in the orchestrator. Each pagination branch stops independently when it encounters a page where all items are already scraped. This global setting is disabled by default but can be enabled as an additional stop condition.
caught_up_threshold
class-attribute
instance-attribute
¶
Global stop threshold: stop after this many consecutive caught-up pages.
Only applies when stop_on_caught_up=True. For multi-seed crawls, prefer the default per-branch stopping which handles each seed independently.
jitter
class-attribute
instance-attribute
¶
Small random delay (0 to jitter seconds) before each request.
items_from
class-attribute
instance-attribute
¶
Which URL types to save items from: "item", "pagination", or "all".
checkpoint_every
class-attribute
instance-attribute
¶
Checkpoint after this many items extracted.
should_retry
¶
Determine if a failed request should be retried.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
CrawlError
|
The error that occurred |
required |
attempts
|
int
|
Number of attempts already made (including the failed one) |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the request should be retried |
Source code in src/databrew/core/policy.py
get_retry_delay
¶
Calculate delay before next retry.
Uses exponential backoff: delay * (backoff_factor ^ attempts)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attempts
|
int
|
Number of attempts already made |
required |
Returns:
| Type | Description |
|---|---|
float
|
Delay in seconds before next attempt |
Source code in src/databrew/core/policy.py
should_stop
¶
should_stop(requests_completed, items_extracted, consecutive_failures, total_failures, consecutive_caught_up=0)
Determine if crawling should stop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requests_completed
|
int
|
Successful requests so far (retries don't count) |
required |
items_extracted
|
int
|
Total items extracted so far (for logging) |
required |
consecutive_failures
|
int
|
Current streak of consecutive failures |
required |
total_failures
|
int
|
Total failures so far |
required |
consecutive_caught_up
|
int
|
Pages where all items were already scraped |
0
|
Returns:
| Type | Description |
|---|---|
tuple[bool, str]
|
Tuple of (should_stop, reason) |
Source code in src/databrew/core/policy.py
should_checkpoint
¶
Determine if a checkpoint should be saved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items_since_last
|
int
|
Items extracted since last checkpoint |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if a checkpoint should be saved |
Source code in src/databrew/core/policy.py
CrawlResult
dataclass
¶
CrawlStats
dataclass
¶
Runtime statistics for a crawl.
Tracks counts needed for policy decisions (stopping rules) and progress reporting.
Source code in src/databrew/core/stats.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
consecutive_caught_up
class-attribute
instance-attribute
¶
Consecutive listing pages where all items were already scraped.
record_success
¶
Record a successful URL processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items_count
|
int
|
Number of items extracted from this URL |
0
|
caught_up
|
bool
|
True if this page had items but all were already scraped |
False
|
Source code in src/databrew/core/stats.py
record_failure
¶
Record a failed URL processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
will_retry
|
bool
|
If True, URL will be retried (not a terminal failure) |
False
|
Source code in src/databrew/core/stats.py
record_queued
¶
record_checkpoint
¶
summary
¶
Return a summary dict for logging/reporting.
Source code in src/databrew/core/stats.py
Extractors¶
Extract structured data from HTML and JSON responses.
HtmlExtractor
¶
Extractor for HTML content using CSS selectors.
Example config:
config = HtmlExtractorConfig(
items=ItemsConfig(
selector=".product-card",
fields={
"title": "h2.title", # Shorthand
"price": FieldConfig(selector=".price", parser="parse_price"),
"url": FieldConfig(selector="a", attribute="href"),
}
),
links=LinksConfig(
selectors=["a.next-page", ".product-card a.detail"]
)
)
extractor = HtmlExtractor(config)
Source code in src/databrew/extract/html.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
extract
¶
Extract items and links from HTML content.
Source code in src/databrew/extract/html.py
JsonExtractor
¶
Extractor for JSON content using dot-notation paths.
Example config:
config = JsonExtractorConfig(
items=JsonItemsConfig(
path="listings.data",
fields={
"id": "ListingID", # Shorthand
"title": JsonFieldConfig(path="Title", required=True),
"price": JsonFieldConfig(path="Price", parser="parse_price"),
}
),
links=JsonLinksConfig(
paths=["listings.next_page_url"],
template="https://api.example.com/items/{id}",
template_path="listings.data.*.ListingID"
)
)
extractor = JsonExtractor(config)
Source code in src/databrew/extract/json.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | |
extract
¶
Extract items and links from JSON content.
Source code in src/databrew/extract/json.py
register_parser
¶
Register a parser function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name to register the parser under |
required |
func
|
Callable
|
Parser function (text -> value) or element parser (Tag -> value) |
required |
Source code in src/databrew/extract/_parsers.py
Fetchers¶
Fetch web content via HTTP or browser automation.
HttpxFetcher
¶
Fetcher using httpx.
Features: - Async HTTP client with connection pooling - Request pacing with jitter - Exponential backoff on 429 errors - Automatic JSON detection - Never raises exceptions (returns FetchResult) - No retry logic (orchestrator handles that)
Source code in src/databrew/fetch/httpx.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
__init__
¶
Initialize the fetcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pacer
|
RequestPacer | None
|
Optional request pacer (creates default if None) |
None
|
timeout
|
float
|
Request timeout in seconds |
30.0
|
headers
|
dict[str, str] | None
|
Default headers for all requests |
None
|
follow_redirects
|
bool
|
Whether to follow redirects |
True
|
Source code in src/databrew/fetch/httpx.py
fetch
async
¶
Fetch content from a URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to fetch |
required |
headers
|
dict[str, str] | None
|
Additional headers to merge with defaults (from middleware) |
None
|
Never raises exceptions - always returns FetchResult.
Source code in src/databrew/fetch/httpx.py
register_fetcher
¶
Register a fetcher factory function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name to register the fetcher under (e.g., "httpx", "pydoll") |
required |
factory
|
FetcherFactory
|
Factory function that creates a fetcher instance. Signature: (config: dict, pacer: RequestPacer | None) -> Fetcher |
required |
Example
Source code in src/databrew/fetch/_registry.py
Storage¶
URL queue and item storage.
StateStore
¶
Unified SQLite store for crawl state and extracted data.
Coordinates: - URL queue management (pagination + item URLs) - Item storage with deduplication
Example
store = StateStore(
"data/mysite/state.db",
id_field="property_id",
)
# URL queue
store.add_pagination_url("https://example.com/listings")
store.add_item_urls(["https://example.com/item/1", "https://example.com/item/2"])
# Save items
store.save_item({"property_id": "123", "price": 100000}, url)
# Export
store.export_jsonl("output.jsonl")
Source code in src/databrew/state/store.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 | |
__init__
¶
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
Path | str
|
Path to SQLite database file |
required |
id_field
|
str | None
|
JSON field name to use as item ID (e.g., "property_id") |
None
|
Source code in src/databrew/state/store.py
add_pagination_url
¶
add_pagination_urls
¶
reset_pagination
¶
add_item_url
¶
add_item_urls
¶
get_next_url
¶
mark_url_done
¶
mark_url_failed
¶
schedule_url_retry
¶
reset_in_progress
¶
clear_urls
¶
url_pending_count
¶
url_completed_count
¶
url_failed_count
¶
url_permanently_failed_count
¶
reset_failed_items
¶
Reset failed item URLs for retry.
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
Tuple of (reset_count, permanently_failed_count) |
Source code in src/databrew/state/store.py
has_item
¶
has_item_for_url
¶
save_item
¶
get_item
¶
get_item_by_url
¶
item_count
¶
iter_items
¶
export_jsonl
¶
Export items to JSONL file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path | str
|
Output file path |
required |
include_meta
|
bool
|
Include _source_url, _extracted_at metadata |
False
|
url_type
|
str | None
|
Filter by URL type ("item", "pagination", or None for all) |
'item'
|
since
|
str | None
|
ISO timestamp - only export items extracted after this time |
None
|
Uses DuckDB fast path when available and metadata not requested.
Source code in src/databrew/state/store.py
export_json
¶
Export items to JSON array file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path | str
|
Output file path |
required |
include_meta
|
bool
|
Include _source_url, _extracted_at metadata |
False
|
url_type
|
str | None
|
Filter by URL type ("item", "pagination", or None for all) |
'item'
|
since
|
str | None
|
ISO timestamp - only export items extracted after this time |
None
|
Source code in src/databrew/state/store.py
export_individual
¶
Export each item to its own JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
Path | str
|
Output directory path |
required |
include_meta
|
bool
|
Include _source_url, _extracted_at metadata |
False
|
url_type
|
str | None
|
Filter by URL type ("item", "pagination", or None for all) |
'item'
|
since
|
str | None
|
ISO timestamp - only export items extracted after this time |
None
|
Falls back to URL hash for filename when id_field is configured but missing. Uses parallel writes for speed.
Source code in src/databrew/state/store.py
export_parquet
¶
Export items to Parquet file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path | str
|
Output file path |
required |
include_meta
|
bool
|
Include _source_url, _extracted_at metadata |
False
|
url_type
|
str | None
|
Filter by URL type ("item", "pagination", or None for all) |
'item'
|
since
|
str | None
|
ISO timestamp - only export items extracted after this time |
None
|
Uses DuckDB fast path when available, falls back to pyarrow.
Source code in src/databrew/state/store.py
import_items
¶
import_items(input_path, url_type='item', source_url_field=None, source_url_prefix=None, batch_size=100, progress_callback=None)
Import items from JSONL, JSON, Parquet, or directory of JSON files.
Uses batched inserts for fast bulk import while preserving timestamps.
Supports all export formats: - .jsonl files (one JSON object per line) - .json files (array of objects) - .parquet files (requires pyarrow) - Directory of individual .json files
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path | str
|
Path to file or directory |
required |
url_type
|
str
|
URL type to assign ('item' or 'pagination') |
'item'
|
source_url_field
|
str | None
|
Dot-notation path to source URL field (e.g., 'advert.url'). If not provided, looks for _source_url metadata. |
None
|
source_url_prefix
|
str | None
|
Prefix to prepend to source URL (e.g., 'https://example.com/item/') |
None
|
batch_size
|
int
|
Commit every N items (default 100) |
100
|
progress_callback
|
Callable[[int, int, int], None] | None
|
Optional callback(imported, skipped, failed) for progress |
None
|
Returns:
| Type | Description |
|---|---|
tuple[int, int, int]
|
Tuple of (items_imported, items_skipped, items_failed) |
Source code in src/databrew/state/store.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
stats
¶
Get store statistics.
Source code in src/databrew/state/store.py
StoredItem
dataclass
¶
UrlTask
dataclass
¶
Middleware¶
Hooks for customizing crawl behavior.
Middleware
¶
Bases: ABC
Base class for middleware.
Override any of the hook methods to customize behavior. All methods receive and return a MiddlewareContext.
The default implementations pass through unchanged.
Source code in src/databrew/middleware.py
pre_fetch
async
¶
Called before fetching a URL.
Use cases: - Add authentication headers - Filter out certain URLs (set ctx.skip = True) - Modify the URL - Log or track URLs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
MiddlewareContext
|
Context with url, headers, url_type |
required |
Returns:
| Type | Description |
|---|---|
MiddlewareContext
|
Modified context (or set ctx.skip=True to skip URL) |
Source code in src/databrew/middleware.py
post_fetch
async
¶
Called after successful fetch, before extraction.
Use cases: - Transform content (decode, decompress) - Cache responses - Detect and handle login pages - Modify content before extraction
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
MiddlewareContext
|
Context with url, content |
required |
Returns:
| Type | Description |
|---|---|
MiddlewareContext
|
Modified context (can replace ctx.content) |
Source code in src/databrew/middleware.py
post_extract
async
¶
Called after extraction.
Use cases: - Enrich items (add fields, geocode addresses) - Filter or transform items - Filter links (remove certain patterns) - Validate extracted data
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
MiddlewareContext
|
Context with url, content, extract_result |
required |
Returns:
| Type | Description |
|---|---|
MiddlewareContext
|
Modified context (can modify ctx.extract_result) |
Source code in src/databrew/middleware.py
on_error
async
¶
Called when an error occurs.
Use cases: - Custom error logging - Error recovery (clear ctx.error to suppress) - Transform errors - Trigger alerts
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
MiddlewareContext
|
Context with url, error |
required |
Returns:
| Type | Description |
|---|---|
MiddlewareContext
|
Modified context (clear ctx.error to suppress and retry) |
Source code in src/databrew/middleware.py
MiddlewareContext
dataclass
¶
Context passed through the middleware chain.
Middleware can read and modify this context to affect the crawl.
The data dict is for middleware to pass data to later stages.
Source code in src/databrew/middleware.py
headers
class-attribute
instance-attribute
¶
Headers to send with the request (can be modified by pre_fetch).
content
class-attribute
instance-attribute
¶
Fetched content (available in post_fetch and later).
extract_result
class-attribute
instance-attribute
¶
Extraction result (available in post_extract).
error
class-attribute
instance-attribute
¶
Error if one occurred (available in on_error).
skip
class-attribute
instance-attribute
¶
Set to True in pre_fetch to skip this URL entirely.
data
class-attribute
instance-attribute
¶
Arbitrary data for middleware to pass between stages.
HeaderMiddleware
¶
Bases: Middleware
Adds headers to all requests.
Source code in src/databrew/middleware.py
UrlFilterMiddleware
¶
Bases: Middleware
Filters URLs based on patterns.
Example
Source code in src/databrew/middleware.py
LoggingMiddleware
¶
Bases: Middleware
Logs all requests and responses.
Source code in src/databrew/middleware.py
Types¶
Core data types and error handling.
PageContent
dataclass
¶
Content fetched from a URL.
This is the interface between fetchers and extractors.
Source code in src/databrew/core/types.py
FetchResult
dataclass
¶
Result of a fetch operation.
Fetchers always return FetchResult, never raise exceptions.
Check success to determine if fetch succeeded.
Source code in src/databrew/core/types.py
ok
classmethod
¶
ExtractResult
dataclass
¶
Result of an extraction operation.
Contains extracted items and links to follow.
Links are split into two categories: - pagination_links: Always added to queue (listing/category pages) - item_links: Checked against storage before adding (detail pages)
Source code in src/databrew/core/types.py
items
class-attribute
instance-attribute
¶
Extracted data items to save.
pagination_links
class-attribute
instance-attribute
¶
Pagination URLs (always followed).
item_links
class-attribute
instance-attribute
¶
Item/detail page URLs (checked against storage).
ok
classmethod
¶
Create a successful extraction result.
Source code in src/databrew/core/types.py
CrawlError
dataclass
¶
Unified error representation.
All errors in the system are represented as CrawlError instances, not exceptions. This enables consistent error handling and retry logic.
Source code in src/databrew/core/types.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
from_exception
classmethod
¶
Classify an exception into a CrawlError.
Source code in src/databrew/core/types.py
extraction_error
classmethod
¶
Create an extraction error.
config_error
classmethod
¶
Create a configuration error (never retryable).
ErrorCategory
¶
Bases: str, Enum
Categories of errors for retry decision making.