@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
References
- AddRequestsBatchedOptions
- AddRequestsBatchedResult
- ApifyLogAdapter
- ArgumentValidationError
- BaseCrawleeLogger
- BLOCKED_STATUS_CODES
- CalculatedStatistics
- coerceBoolean
- coerceNumber
- ConcurrencyConsumer
- ConcurrencySystem
- ConcurrencySystemOptions
- ConfigField
- Configuration
- ConfigurationInput
- ConfigurationOptions
- ContextMiddleware
- ContextPipeline
- ContextPipelineCleanupError
- ContextPipelineInitializationError
- ContextPipelineInterruptedError
- CpuLoadSignal
- CpuLoadSignalOptions
- crawleeConfigFields
- CrawleeLogger
- CrawleeLoggerOptions
- CrawlingContext
- CreateSession
- createStorageTransaction
- CriticalError
- Dataset
- DatasetConsumer
- DatasetContent
- DatasetDataOptions
- DatasetExportOptions
- DatasetExportToOptions
- DatasetIteratorOptions
- DatasetJournalEntry
- DatasetMapper
- DatasetOptions
- DatasetReducer
- DatasetStats
- defaultRoute
- DefaultRouteUserData
- DefaultStorageIdentifier
- EnqueueLinksOptions
- EnqueueStrategy
- EnqueueStrategyOption
- EnqueueUrlsOptions
- ErrnoException
- ErrorSnapshotter
- ErrorTracker
- ErrorTrackerOptions
- EventLoopLoadSignal
- EventLoopLoadSignalOptions
- EventManager
- EventManagerOptions
- EventStatusMessageData
- EventType
- EventTypeName
- ExplicitStorageIdentifier
- ExtractLinksOptions
- field
- FieldsInput
- FieldsOutput
- FinalStatistics
- GetUserDataFromRequest
- GlobInput
- GlobObject
- IConcurrencySystem
- IProxyConfiguration
- IRequestLoader
- IRequestManager
- IStatistics
- IStorage
- JournaledRequest
- JournalEntry
- KeyConsumer
- KeyValueStore
- KeyValueStoreIteratorOptions
- KeyValueStoreJournalEntry
- KeyValueStoreOptions
- KeyValueStoreRawRecord
- KeyValueStoreStats
- LabeledSource
- LoadedRequest
- LoadSignal
- LoadSignalInfo
- LoadSignalsOptions
- LoadSignalStartContext
- LoadSnapshot
- LocalEventManager
- LocalEventManagerOptions
- log
- Log
- Logger
- LoggerJson
- LoggerOptions
- LoggerText
- LogLevel
- MAX_POOL_SIZE
- MemoryLoadSignal
- MemoryLoadSignalOptions
- MemoryStorageBackend
- MemoryStorageOptions
- MissingSessionError
- NavigationSkippedError
- NonRetryableError
- parseRetryAfterHeader
- parseValue
- PERSIST_STATE_KEY
- PersistenceOptions
- PersistentRateLimitError
- ProxyConfiguration
- ProxyConfigurationFunction
- ProxyConfigurationOptions
- purgeDefaultStorages
- PushErrorMessageOptions
- RecordOptions
- RecoverableState
- RecoverableStateOptions
- RecoverableStatePersistenceOptions
- RegExpInput
- RegExpObject
- Request
- RequestHandlerError
- RequestList
- RequestListOptions
- RequestListSourcesFunction
- RequestListState
- RequestManagerOpener
- RequestManagerTandem
- RequestOptions
- RequestQueue
- RequestQueueJournalEntry
- RequestQueueOperationInfo
- RequestQueueOperationOptions
- RequestQueueOptions
- RequestQueueStats
- RequestsLike
- RequestState
- RequestThrottledError
- RequestTransform
- RequestValidationError
- ResolvedConfigValues
- resolveStorageIdentifier
- ResponseLike
- RestrictedCrawlingContext
- RetryRequestError
- RouteOptions
- Router
- RouterHandler
- RouterHandlerContext
- RouterLabel
- RouterRoutes
- RouteSchemas
- RoutesFromSchemas
- SchemaIssue
- serializeValue
- ServiceConflictError
- serviceLocator
- ServiceLocator
- Session
- SessionError
- SessionOptions
- SessionPool
- SessionPoolOptions
- SessionReuseStrategy
- SitemapRequestLoader
- SitemapRequestLoaderOptions
- SkippedRequestCallback
- SkippedRequestReason
- SnapshotResult
- SnapshotStore
- Source
- StateConversion
- StateValidationError
- StatisticPersistedState
- Statistics
- StatisticsOptions
- StatisticState
- StatisticStateExtensionOptions
- StorageBackend
- StorageBackendLoadSignal
- StorageBackendLoadSignalOptions
- StorageIdentifier
- StorageInstanceManager
- StorageOpenOptions
- StorageStatsTracker
- StorageTransaction
- StorageTransactionOptions
- StorageTransactionState
- StorageTransactionView
- StorageWriteMode
- StorageWritePolicy
- supportsDomainThrottling
- SupportsDomainThrottling
- SyncStateConversion
- SystemInfo
- TaskLoopOptions
- TaskLoopPredicates
- ThrottlingRequestManager
- ThrottlingRequestManagerOptions
- TypedContextAddRequests
- TypedContextEnqueueLinks
- UrlPatternInput
- UrlPatternObject
- useState
- UseStateOptions
- withDirectStorageAccess
- WithRequired
- withStorageTransaction
Classes
Interfaces
Type Aliases
Functions
References
AddRequestsBatchedOptions
AddRequestsBatchedResult
ApifyLogAdapter
ArgumentValidationError
BaseCrawleeLogger
BLOCKED_STATUS_CODES
CalculatedStatistics
coerceBoolean
coerceNumber
ConcurrencyConsumer
ConcurrencySystem
ConcurrencySystemOptions
ConfigField
Configuration
ConfigurationInput
ConfigurationOptions
ContextMiddleware
ContextPipeline
ContextPipelineCleanupError
ContextPipelineInitializationError
ContextPipelineInterruptedError
CpuLoadSignal
CpuLoadSignalOptions
crawleeConfigFields
CrawleeLogger
CrawleeLoggerOptions
CrawlingContext
CreateSession
createStorageTransaction
CriticalError
Dataset
DatasetConsumer
DatasetContent
DatasetDataOptions
DatasetExportOptions
DatasetExportToOptions
DatasetIteratorOptions
DatasetJournalEntry
DatasetMapper
DatasetOptions
DatasetReducer
DatasetStats
defaultRoute
DefaultRouteUserData
DefaultStorageIdentifier
EnqueueLinksOptions
EnqueueStrategy
EnqueueStrategyOption
EnqueueUrlsOptions
ErrnoException
ErrorSnapshotter
ErrorTracker
ErrorTrackerOptions
EventLoopLoadSignal
EventLoopLoadSignalOptions
EventManager
EventManagerOptions
EventStatusMessageData
EventType
EventTypeName
ExplicitStorageIdentifier
ExtractLinksOptions
field
FieldsInput
FieldsOutput
FinalStatistics
GetUserDataFromRequest
GlobInput
GlobObject
IConcurrencySystem
IProxyConfiguration
IRequestLoader
IRequestManager
IStatistics
IStorage
JournaledRequest
JournalEntry
KeyConsumer
KeyValueStore
KeyValueStoreIteratorOptions
KeyValueStoreJournalEntry
KeyValueStoreOptions
KeyValueStoreRawRecord
KeyValueStoreStats
LabeledSource
LoadedRequest
LoadSignal
LoadSignalInfo
LoadSignalsOptions
LoadSignalStartContext
LoadSnapshot
LocalEventManager
LocalEventManagerOptions
log
Log
Logger
LoggerJson
LoggerOptions
LoggerText
LogLevel
MAX_POOL_SIZE
MemoryLoadSignal
MemoryLoadSignalOptions
MemoryStorageBackend
MemoryStorageOptions
MissingSessionError
NavigationSkippedError
NonRetryableError
parseRetryAfterHeader
parseValue
PERSIST_STATE_KEY
PersistenceOptions
PersistentRateLimitError
ProxyConfiguration
ProxyConfigurationFunction
ProxyConfigurationOptions
purgeDefaultStorages
PushErrorMessageOptions
RecordOptions
RecoverableState
RecoverableStateOptions
RecoverableStatePersistenceOptions
RegExpInput
RegExpObject
Request
RequestHandlerError
RequestList
RequestListOptions
RequestListSourcesFunction
RequestListState
RequestManagerOpener
RequestManagerTandem
RequestOptions
RequestQueue
RequestQueueJournalEntry
RequestQueueOperationInfo
RequestQueueOperationOptions
RequestQueueOptions
RequestQueueStats
RequestsLike
RequestState
RequestThrottledError
RequestTransform
RequestValidationError
ResolvedConfigValues
resolveStorageIdentifier
ResponseLike
RestrictedCrawlingContext
RetryRequestError
RouteOptions
Router
RouterHandler
RouterHandlerContext
RouterLabel
RouterRoutes
RouteSchemas
RoutesFromSchemas
SchemaIssue
serializeValue
ServiceConflictError
serviceLocator
ServiceLocator
Session
SessionError
SessionOptions
SessionPool
SessionPoolOptions
SessionReuseStrategy
SitemapRequestLoader
SitemapRequestLoaderOptions
SkippedRequestCallback
SkippedRequestReason
SnapshotResult
SnapshotStore
Source
StateConversion
StateValidationError
StatisticPersistedState
Statistics
StatisticsOptions
StatisticState
StatisticStateExtensionOptions
StorageBackend
StorageBackendLoadSignal
StorageBackendLoadSignalOptions
StorageIdentifier
StorageInstanceManager
StorageOpenOptions
StorageStatsTracker
StorageTransaction
StorageTransactionOptions
StorageTransactionState
StorageTransactionView
StorageWriteMode
StorageWritePolicy
supportsDomainThrottling
SupportsDomainThrottling
SyncStateConversion
SystemInfo
TaskLoopOptions
TaskLoopPredicates
ThrottlingRequestManager
ThrottlingRequestManagerOptions
TypedContextAddRequests
TypedContextEnqueueLinks
UrlPatternInput
UrlPatternObject
useState
UseStateOptions
withDirectStorageAccess
WithRequired
withStorageTransaction
Type Aliases
ErrorHandler
Type parameters
- BaseContext: CrawlingContext = CrawlingContext
- ExtendedContext: BaseContext = BaseContext
Type declaration
Parameters
inputs: BaseContext & Partial<ExtendedContext>
error: Error
Returns Awaitable<void>
RequestHandler
Type parameters
- Context: CrawlingContext = CrawlingContext
Type declaration
Parameters
inputs: Context
Returns Awaitable<void>
RequireContextPipeline
Type parameters
- DefaultContextType: CrawlingContext
- FinalContextType: DefaultContextType
StatusMessageCallback
Type parameters
- Context: CrawlingContext = BasicCrawlingContext
- Crawler: BasicCrawler<any, any, any, any> = BasicCrawler<Context>
Type declaration
Parameters
params: StatusMessageCallbackParams<Context, Crawler>
Returns Awaitable<void>
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
BaseContextis guaranteed to be present, while the extra properties added by the pipeline andextendContext(the difference betweenBaseContextandExtendedContext) are only available as aPartial.