@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
- DatasetJournalEntry
- DatasetMapper
- DatasetOptions
- DatasetReducer
- DatasetStats
- DefaultStorageIdentifier
- EnqueueStrategy
- EnqueueStrategyOption
- EventManager
- EventManagerOptions
- EventStatusMessageData
- EventType
- EventTypeName
- ExplicitStorageIdentifier
- field
- FieldsInput
- FieldsOutput
- IProxyConfiguration
- IRequestLoader
- IRequestManager
- IStorage
- JournaledRequest
- JournalEntry
- KeyConsumer
- KeyValueStore
- KeyValueStoreIteratorOptions
- KeyValueStoreJournalEntry
- KeyValueStoreOptions
- KeyValueStoreRawRecord
- KeyValueStoreStats
- LoadSignalInfo
- LocalEventManager
- LocalEventManagerOptions
- log
- Log
- Logger
- LoggerJson
- LoggerOptions
- LoggerText
- LogLevel
- LogOptions
- MemoryStorageBackend
- MemoryStorageOptions
- NonRetryableError
- PacingScope
- PacingSignal
- parseValue
- ProxyConfiguration
- ProxyConfigurationFunction
- ProxyConfigurationOptions
- purgeDefaultStorages
- PushErrorMessageOptions
- RecordOptions
- RecoverableState
- RecoverableStateOptions
- RecoverableStatePersistenceOptions
- Request
- RequestList
- RequestListOptions
- RequestListSourcesFunction
- RequestListState
- RequestLoaderStatus
- RequestManagerTandem
- RequestOptions
- RequestQueue
- RequestQueueJournalEntry
- RequestQueueOperationInfo
- RequestQueueOperationOptions
- RequestQueueOptions
- RequestQueueStats
- RequestsLike
- RequestSourceStatus
- RequestState
- RequestValidationError
- ResolvedConfigValues
- resolveStorageIdentifier
- SchemaIssue
- serializeValue
- ServiceConflictError
- serviceLocator
- ServiceLocator
- SessionError
- SkippedRequestReason
- Source
- StateConversion
- StateValidationError
- StorageBackend
- StorageIdentifier
- StorageInstanceManager
- StorageOpenOptions
- StorageStatsTracker
- StorageTransaction
- StorageTransactionOptions
- StorageTransactionState
- StorageTransactionView
- StorageWriteMode
- StorageWritePolicy
- SyncStateConversion
- SystemInfo
- useState
- UseStateOptions
- withDirectStorageAccess
- withStorageTransaction
- BasicCrawler
- ContextPipeline
- ContextPipelineCleanupError
- ContextPipelineInitializationError
- ContextPipelineInterruptedError
- ErrorSnapshotter
- ErrorTracker
- MissingSessionError
- NavigationSkippedError
- PersistentRateLimitError
- RequestHandlerError
- RequestThrottledError
- RetryRequestError
- Router
- SitemapRequestLoader
- SnapshotStore
- BasicCrawlerOptions
- BasicCrawlingContext
- CalculatedStatistics
- ConcurrencySystemOptions
- ContextMiddleware
- CpuLoadSignalOptions
- CrawlerAddRequestsOptions
- CrawlerAddRequestsResult
- CrawlerRunOptions
- CrawlingContext
- CreateContextOptions
- CreateSession
- EnqueueUrlsOptions
- ErrnoException
- ErrorTrackerOptions
- EventLoopLoadSignalOptions
- ExtractLinksOptions
- FinalStatistics
- GlobObject
- LoadSignal
- LoadSignalsOptions
- LoadSignalStartContext
- LoadSnapshot
- MemoryLoadSignalOptions
- PersistenceOptions
- RegExpObject
- RequestTransform
- ResponseLike
- RestrictedCrawlingContext
- RouteOptions
- RouterHandler
- SessionOptions
- SessionPoolOptions
- SitemapRequestLoaderOptions
- SnapshotResult
- StatisticPersistedState
- StatisticsOptions
- StatisticState
- StatisticStateExtensionOptions
- StatusMessageCallbackParams
- StorageBackendLoadSignalOptions
- TaskLoopOptions
- TaskLoopPredicates
- ThrottlingRequestManagerOptions
- UrlPatternObject
- DefaultRouteUserData
- EnqueueLinksOptions
- ErrorHandler
- GetUserDataFromRequest
- GlobInput
- LabeledSource
- LoadedRequest
- RegExpInput
- RequestHandler
- RequestManagerOpener
- RequireContextPipeline
- RouterHandlerContext
- RouterLabel
- RouterRoutes
- RouteSchemas
- RoutesFromSchemas
- SessionReuseStrategy
- SkippedRequestCallback
- StatusMessageCallback
- TypedContextAddRequests
- TypedContextEnqueueLinks
- TypedRequestsLike
- UrlPatternInput
- WithRequired
- BLOCKED_STATUS_CODES
- defaultRoute
- MAX_POOL_SIZE
- PERSIST_STATE_KEY
- 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
DatasetJournalEntry
DatasetMapper
DatasetOptions
DatasetReducer
DatasetStats
DefaultStorageIdentifier
EnqueueStrategy
EnqueueStrategyOption
EventManager
EventManagerOptions
EventStatusMessageData
EventType
EventTypeName
ExplicitStorageIdentifier
field
FieldsInput
FieldsOutput
IProxyConfiguration
IRequestLoader
IRequestManager
IStorage
JournaledRequest
JournalEntry
KeyConsumer
KeyValueStore
KeyValueStoreIteratorOptions
KeyValueStoreJournalEntry
KeyValueStoreOptions
KeyValueStoreRawRecord
KeyValueStoreStats
LoadSignalInfo
LocalEventManager
LocalEventManagerOptions
log
Log
Logger
LoggerJson
LoggerOptions
LoggerText
LogLevel
LogOptions
MemoryStorageBackend
MemoryStorageOptions
NonRetryableError
PacingScope
PacingSignal
parseValue
ProxyConfiguration
ProxyConfigurationFunction
ProxyConfigurationOptions
purgeDefaultStorages
PushErrorMessageOptions
RecordOptions
RecoverableState
RecoverableStateOptions
RecoverableStatePersistenceOptions
Request
RequestList
RequestListOptions
RequestListSourcesFunction
RequestListState
RequestLoaderStatus
RequestManagerTandem
RequestOptions
RequestQueue
RequestQueueJournalEntry
RequestQueueOperationInfo
RequestQueueOperationOptions
RequestQueueOptions
RequestQueueStats
RequestsLike
RequestSourceStatus
RequestState
RequestValidationError
ResolvedConfigValues
resolveStorageIdentifier
SchemaIssue
serializeValue
ServiceConflictError
serviceLocator
ServiceLocator
SessionError
SkippedRequestReason
Source
StateConversion
StateValidationError
StorageBackend
StorageIdentifier
StorageInstanceManager
StorageOpenOptions
StorageStatsTracker
StorageTransaction
StorageTransactionOptions
StorageTransactionState
StorageTransactionView
StorageWriteMode
StorageWritePolicy
SyncStateConversion
SystemInfo
useState
UseStateOptions
withDirectStorageAccess
withStorageTransaction
DefaultRouteUserData
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
Type parameters
- R: Request
RegExpInput
RequestHandler
Type parameters
- Context: CrawlingContext = CrawlingContext
Type declaration
Parameters
inputs: Context
Returns Awaitable<void>
RequestManagerOpener
Opens a request manager, matching the shape of storage open methods such as
RequestQueue.open.
ThrottlingRequestManager calls this once per configured domain, so every per-domain queue shares the concrete type and storage backend of the manager being wrapped.
Type parameters
Type declaration
Parameters
optionalidentifier: string | StorageIdentifier | null
optionaloptions: StorageOpenOptions
Returns Promise<T>
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>
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.
WithRequired
Type parameters
- T
- K: keyof T
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).
The
userDatatype of the default route: inferred from the defaultRoute schema when the route map carries one, otherwise the providedFallback.