@crawlee/basic
Provides a simple framework for parallel crawling of web pages. The URLs to crawl are fed either from a static list of URLs or from a dynamic queue of URLs enabling recursive crawling of websites.
BasicCrawler is a low-level tool that requires the user to implement the page download and data extraction functionality themselves.
If we want a crawler that already facilitates this functionality, we should consider using CheerioCrawler, PuppeteerCrawler or PlaywrightCrawler.
BasicCrawler invokes the user-provided requestHandler for each Request object, which represents a single URL to crawl. The Request objects are fed from the RequestList or RequestQueue instances provided by the requestList or requestQueue constructor options, respectively. If neither requestList nor requestQueue options are provided, the crawler will open the default request queue either when the crawler.addRequests() function is called, or if requests parameter (representing the initial requests) of the crawler.run() function is provided.
If both requestList and requestQueue options are used, the instance first processes URLs from the RequestList and automatically enqueues all of them to the RequestQueue before it starts their processing. This ensures that a single URL is not crawled multiple times.
The crawler finishes if there are no more Request objects to crawl.
New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's ConcurrencySystem. Concurrency is tuned via the minConcurrency, maxConcurrency and maxRequestsPerMinute options of the BasicCrawler constructor, or, for finer control, by injecting a pre-configured concurrencySystem.
Example usage
import { BasicCrawler, Dataset } from 'crawlee';
// Create a crawler instance
const crawler = new BasicCrawler({
async requestHandler({ request, sendRequest }) {
// 'request' contains an instance of the Request class
// Here we simply fetch the HTML of the page and store it to a dataset
const { body } = await sendRequest({
url: request.url,
method: request.method,
body: request.payload,
headers: request.headers,
});
await Dataset.pushData({
url: request.url,
html: body,
})
},
});
// Enqueue the initial requests and run the crawler
await crawler.run([
'http://www.example.com/page-1',
'http://www.example.com/page-2',
]);
Index
Crawlers
Scaling
Sources
Other
- AddRequestsBatchedOptions
- AddRequestsBatchedResult
- AfterCommitError
- ApifyLogAdapter
- ArgumentValidationError
- BaseCrawleeLogger
- coerceBoolean
- coerceNumber
- ConfigField
- Configuration
- ConfigurationInput
- ConfigurationOptions
- crawleeConfigFields
- CrawleeLogger
- CrawleeLoggerOptions
- createStorageTransaction
- CriticalError
- Dataset
- DatasetConsumer
- DatasetContent
- DatasetDataOptions
- DatasetExportOptions
- DatasetExportToOptions
- DatasetIteratorOptions
- DatasetMapper
- DatasetReducer
- DatasetStats
- DefaultStorageIdentifier
- EnqueueStrategy
- EnqueueStrategyOption
- EventManager
- EventManagerOptions
- EventStatusMessageData
- EventType
- EventTypeName
- ExplicitStorageIdentifier
- field
- FieldsInput
- FieldsOutput
- IProxyConfiguration
- IRequestLoader
- IRequestManager
- IStorage
- KeyConsumer
- KeyValueStore
- KeyValueStoreIteratorOptions
- KeyValueStoreRawRecord
- KeyValueStoreStats
- LoadSignalInfo
- LocalEventManager
- LocalEventManagerOptions
- log
- Log
- Logger
- LoggerJson
- LoggerOptions
- LoggerText
- LogLevel
- LogOptions
- MemoryStorageBackend
- MemoryStorageOptions
- NonRetryableError
- PacingScope
- PacingSignal
- parseValue
- ProxyConfiguration
- ProxyConfigurationFunction
- ProxyConfigurationOptions
- purgeDefaultStorages
- RecordOptions
- RecoverableState
- RecoverableStateBaseOptions
- RecoverableStateOptions
- RecoverableStatePersistenceOptions
- Request
- RequestList
- RequestListOptions
- RequestListSource
- RequestListSourcesFunction
- RequestListState
- RequestLoaderStatus
- RequestManagerTandem
- RequestOptions
- RequestQueue
- RequestQueueOperationInfo
- RequestQueueOperationOptions
- RequestQueueStats
- RequestsLike
- RequestSourceStatus
- RequestValidationError
- ResolvedConfigValues
- SchemaIssue
- serializeValue
- ServiceConflictError
- serviceLocator
- ServiceLocator
- SessionError
- SessionRetiredError
- Source
- StateConversion
- StateValidationError
- StorageBackend
- StorageIdentifier
- StorageInstanceManager
- StorageOpenOptions
- StorageTransaction
- StorageTransactionOptions
- StorageTransactionState
- StorageTransactionView
- StorageWriteMode
- StorageWritePolicy
- SyncStateConversion
- SystemInfo
- useState
- UseStateOptions
- withDirectStorageAccess
- withStorageTransaction
- RequestState
- BasicCrawler
- ContextPipeline
- ContextPipelineCleanupError
- ContextPipelineInitializationError
- ContextPipelineInterruptedError
- ErrorTracker
- MissingSessionError
- NavigationSkippedError
- PersistentRateLimitError
- RequestHandlerError
- RequestThrottledError
- RetryRequestError
- Router
- SitemapRequestLoader
- SnapshotStore
- BasicCrawlerOptions
- BasicCrawlingContext
- CalculatedStatistics
- ConcurrencySystemOptions
- CpuLoadSignalOptions
- CrawlerAddRequestsOptions
- CrawlerAddRequestsResult
- CrawlerRunOptions
- CrawlingContext
- CreateSession
- EnqueueUrlsOptions
- ErrnoException
- ErrorTrackerOptions
- EventLoopLoadSignalOptions
- ExtractLinksOptions
- FinalStatistics
- GlobObject
- LoadSignal
- LoadSignalsOptions
- LoadSignalStartContext
- LoadSnapshot
- MemoryLoadSignalOptions
- PersistenceOptions
- PushErrorMessageOptions
- RegExpObject
- RequestTransform
- RestrictedCrawlingContext
- RouteOptions
- RouterHandler
- SessionOptions
- SessionPoolOptions
- SitemapRequestLoaderOptions
- StatisticPersistedState
- StatisticsOptions
- StatisticState
- StatisticStateExtensionOptions
- StatusMessageCallbackParams
- StorageBackendLoadSignalOptions
- TaskLoopOptions
- TaskLoopPredicates
- ThrottlingRequestManagerOptions
- CleanupRegistrar
- ContextMiddleware
- DefaultRouteUserData
- EnqueueLinksOptions
- ErrorHandler
- GetUserDataFromRequest
- GlobInput
- LabeledSource
- LoadedRequest
- RegExpInput
- RequestHandler
- RequireContextPipeline
- RouterHandlerContext
- RouterLabel
- RouterRoutes
- RouteSchemas
- RoutesFromSchemas
- SessionReuseStrategy
- SkippedRequestCallback
- SkippedRequestReason
- StatusMessageCallback
- TypedContextAddRequests
- TypedContextEnqueueLinks
- TypedRequestsLike
- UrlPatternInput
- BLOCKED_STATUS_CODES
- defaultRoute
- createBasicRouter
- parseRetryAfterHeader
Other
AddRequestsBatchedOptions
AddRequestsBatchedResult
AfterCommitError
ApifyLogAdapter
ArgumentValidationError
BaseCrawleeLogger
coerceBoolean
coerceNumber
ConfigField
Configuration
ConfigurationInput
ConfigurationOptions
crawleeConfigFields
CrawleeLogger
CrawleeLoggerOptions
createStorageTransaction
CriticalError
Dataset
DatasetConsumer
DatasetContent
DatasetDataOptions
DatasetExportOptions
DatasetExportToOptions
DatasetIteratorOptions
DatasetMapper
DatasetReducer
DatasetStats
DefaultStorageIdentifier
EnqueueStrategy
EnqueueStrategyOption
EventManager
EventManagerOptions
EventStatusMessageData
EventType
EventTypeName
ExplicitStorageIdentifier
field
FieldsInput
FieldsOutput
IProxyConfiguration
IRequestLoader
IRequestManager
IStorage
KeyConsumer
KeyValueStore
KeyValueStoreIteratorOptions
KeyValueStoreRawRecord
KeyValueStoreStats
LoadSignalInfo
LocalEventManager
LocalEventManagerOptions
log
Log
Logger
LoggerJson
LoggerOptions
LoggerText
LogLevel
LogOptions
MemoryStorageBackend
MemoryStorageOptions
NonRetryableError
PacingScope
PacingSignal
parseValue
ProxyConfiguration
ProxyConfigurationFunction
ProxyConfigurationOptions
purgeDefaultStorages
RecordOptions
RecoverableState
RecoverableStateBaseOptions
RecoverableStateOptions
RecoverableStatePersistenceOptions
Request
RequestList
RequestListOptions
RequestListSource
RequestListSourcesFunction
RequestListState
RequestLoaderStatus
RequestManagerTandem
RequestOptions
RequestQueue
RequestQueueOperationInfo
RequestQueueOperationOptions
RequestQueueStats
RequestsLike
RequestSourceStatus
RequestValidationError
ResolvedConfigValues
SchemaIssue
serializeValue
ServiceConflictError
serviceLocator
ServiceLocator
SessionError
SessionRetiredError
Source
StateConversion
StateValidationError
StorageBackend
StorageIdentifier
StorageInstanceManager
StorageOpenOptions
StorageTransaction
StorageTransactionOptions
StorageTransactionState
StorageTransactionView
StorageWriteMode
StorageWritePolicy
SyncStateConversion
SystemInfo
useState
UseStateOptions
withDirectStorageAccess
withStorageTransaction
CleanupRegistrar
Type declaration
Parameters
cleanup: (error) => Awaitable<void>
Returns void
ContextMiddleware
A middleware step in the context pipeline: receives the context built so far and returns an extension that gets
merged into it. Anything that needs tearing down is registered via onCleanup.
Type parameters
- TCrawlingContext
The input context type for this middleware
- TCrawlingContextExtension
The enhanced output context type
Type declaration
Parameters
context: TCrawlingContext
onCleanup: CleanupRegistrar
Returns Awaitable<TCrawlingContextExtension>
DefaultRouteUserData
The userData type of the default route: inferred from the defaultRoute schema when the route map
carries one, otherwise the provided Fallback.
Type parameters
- Routes
- Fallback: Dictionary
EnqueueLinksOptions
The combined options accepted by a crawler context's enqueueLinks() helper: extractLinks() + enqueueUrls().
ErrorHandler
An error handler receives the crawling context and the error that was thrown while processing the request.
Unlike the RequestHandler, an error handler may run before the context pipeline has finished
building the full context (e.g. when navigation or session setup fails). Therefore only BaseContext is
guaranteed to be present, while the extra properties added by the pipeline and extendContext (the
difference between BaseContext and ExtendedContext) are only available as a Partial.
Type parameters
- BaseContext: CrawlingContext = CrawlingContext
- ExtendedContext: BaseContext = BaseContext
Type declaration
Parameters
inputs: BaseContext & Partial<ExtendedContext>
error: Error
Returns Awaitable<void>
GetUserDataFromRequest
Type parameters
- T
GlobInput
LabeledSource
A request input (URL string, request-options object, or Request) whose userData is typed
according to its label, based on a router's route map.
When the route map is open (the default Record<string, ...>), this is just the regular loose
Source input. When the map declares concrete labels, providing a label requires the matching
userData shape and rejects labels not present in the map; unlabeled requests keep loose userData.
Type parameters
- Routes: Record<keyof Routes, Dictionary>
LoadedRequest
RegExpInput
RequestHandler
Type parameters
- Context: CrawlingContext = CrawlingContext
Type declaration
Parameters
inputs: Context
Returns Awaitable<void>
RequireContextPipeline
Type parameters
- DefaultContextType: CrawlingContext
- FinalContextType: DefaultContextType
RouterHandlerContext
The crawling context received by a route handler, with request.userData narrowed to UserData, and
addRequests/enqueueLinks typed according to the router's route map (Routes) so that enqueuing a
request under a declared label requires the matching userData shape.
Type parameters
- Context
- UserData: Dictionary
- Routes: Record<keyof Routes, Dictionary>
RouterLabel
The set of labels accepted by Router.addHandler. When the router declares a concrete
route map (e.g. { PRODUCT: ...; CATEGORY: ... }), only those labels (plus symbols) are
allowed — unknown labels become a compile-time error. When the map is left open (the default
Record<string, ...>), any string or symbol label is accepted, preserving the original behaviour.
Type parameters
- Routes: Record<keyof Routes, Dictionary>
RouterRoutes
Type parameters
- Context
- Routes: Record<keyof Routes, Dictionary>
RouteSchemas
A map of request labels to a Standard Schema (Zod, Valibot, ArkType, …)
validating that label's request.userData. Pass it to Router.create or a createXRouter
factory to derive the per-label request.userData types and validate them at runtime. The optional
defaultRoute key registers a schema for requests handled by the default route.
RoutesFromSchemas
Derives a route map (label → userData type) from a RouteSchemas map by inferring each schema's
output type. Outputs that are not object-shaped fall back to a plain Dictionary. The
defaultRoute schema is kept under its symbol key so Router.addDefaultHandler can pick it
up; string labels (the ones Router.addHandler and the crawler-level typing accept) ignore it.
Type parameters
- Schemas: RouteSchemas
SessionReuseStrategy
SkippedRequestCallback
Type declaration
Parameters
args: { reason: SkippedRequestReason; request: Request }
reason: SkippedRequestReason
request: Request
Returns Awaitable<void>
SkippedRequestReason
StatusMessageCallback
Type parameters
- Context: CrawlingContext = BasicCrawlingContext
- Crawler: BasicCrawler<any, any, any, any> = BasicCrawler<Context>
Type declaration
Parameters
params: StatusMessageCallbackParams<Context, Crawler>
Returns Awaitable<void>
TypedContextAddRequests
The label-aware addRequests method signature exposed on a request handler's context when the crawler is
bound to a typed router. Mirrors RestrictedCrawlingContext.addRequests with typed sources.
Type parameters
- Routes: Record<keyof Routes, Dictionary>
Type declaration
Parameters
requestsLike: ReadonlyDeep<LabeledSource<Routes>[]>
optionaloptions: ReadonlyDeep<EnqueueUrlsOptions>
Returns Promise<AddRequestsBatchedResult>
TypedContextEnqueueLinks
Transforms a context's existing enqueueLinks method so that the label/userData in its options follow
the router's route map, while preserving everything else about the signature (argument optionality and
return type, which differ between crawler types).
Type parameters
- EnqueueLinks
- Routes: Record<keyof Routes, Dictionary>
TypedRequestsLike
The iterable/array of LabeledSource inputs accepted by the label-aware addRequests/run
methods of a crawler bound to a typed router.
Type parameters
- Routes: Record<keyof Routes, Dictionary>
UrlPatternInput
Unified URL pattern input — accepts glob strings, glob objects, RegExp instances, or regexp objects.
constBLOCKED_STATUS_CODES
constdefaultRoute
The key of the default route — the fallback handler registered via Router.addDefaultHandler.
Use it in a RouteSchemas map to register a schema that validates the userData of every request
that falls through to the default handler (i.e. whose label has no route of its own).
Registers a callback that runs after the final context consumer finishes. Cleanups run in reverse registration order and receive the same
erroras theonErrorparameter of ContextPipeline.call:undefinedon success, otherwise a ContextPipelineInitializationError (a middleware failed) or a RequestHandlerError (the consumer failed), with the original incause. A cleanup that throws fails the whole call with a ContextPipelineCleanupError, which is critical.