@crawlee/playwright
Provides a simple framework for parallel crawling of web pages using headless Chromium, Firefox and Webkit browsers with Playwright. 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.
Since Playwright uses headless browser to download web pages and extract data, it is useful for crawling of websites that require to execute JavaScript. If the target website doesn't need JavaScript, consider using CheerioCrawler, which downloads the pages using raw HTTP requests and is about 10x faster.
The source URLs are represented using Request objects that are fed from RequestList or RequestQueue instances provided by the PlaywrightCrawlerOptions.requestList or PlaywrightCrawlerOptions.requestQueue constructor options, respectively.
If both PlaywrightCrawlerOptions.requestList and PlaywrightCrawlerOptions.requestQueue are used, the instance first processes URLs from the RequestList and automatically enqueues all of them to RequestQueue before it starts their processing. This ensures that a single URL is not crawled multiple times.
The crawler finishes when there are no more Request objects to crawl.
PlaywrightCrawler opens a new Chrome page (i.e. tab) for each Request object to crawl and then calls the function provided by user as the PlaywrightCrawlerOptions.requestHandler option.
New pages are only opened 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 PlaywrightCrawler constructor, or, for finer control, by injecting a pre-configured concurrencySystem.
Note that the pool of Playwright instances is internally managed by the BrowserPool class.
Example usage
const crawler = new PlaywrightCrawler({
async requestHandler({ page, request }) {
// This function is called to extract data from a single web page
// 'page' is an instance of Playwright.Page with page.goto(request.url) already called
// 'request' is an instance of Request class with information about the page to load
await Dataset.pushData({
title: await page.title(),
url: request.url,
succeeded: true,
})
},
async failedRequestHandler({ request }) {
// This function is called when the crawling of a request failed too many times
await Dataset.pushData({
url: request.url,
succeeded: false,
errors: request.errorMessages,
})
},
});
await crawler.run([
'http://www.example.com/page-1',
'http://www.example.com/page-2',
]);
Index
Browser management
Crawlers
Other
- AddRequestsBatchedOptions
- AddRequestsBatchedResult
- ApifyLogAdapter
- ArgumentValidationError
- assertBrowserPoolNotConfigured
- BaseCrawleeLogger
- BasicCrawler
- BasicCrawlerOptions
- BasicCrawlingContext
- BLOCKED_STATUS_CODES
- BrowserCrawler
- BrowserCrawlerOptions
- BrowserCrawlingContext
- BrowserHook
- BrowserLaunchContext
- CalculatedStatistics
- coerceBoolean
- coerceNumber
- ConcurrencyConsumer
- ConcurrencySystem
- ConcurrencySystemOptions
- ConfigField
- Configuration
- ConfigurationInput
- ConfigurationOptions
- ContextMiddleware
- ContextPipeline
- ContextPipelineCleanupError
- ContextPipelineInitializationError
- ContextPipelineInterruptedError
- CpuLoadSignal
- CpuLoadSignalOptions
- crawleeConfigFields
- CrawleeLogger
- CrawleeLoggerOptions
- CrawlerAddRequestsOptions
- CrawlerAddRequestsResult
- CrawlerRunOptions
- CrawlingContext
- createBasicRouter
- CreateContextOptions
- CreateSession
- createStorageTransaction
- CriticalError
- Dataset
- DatasetConsumer
- DatasetContent
- DatasetDataOptions
- DatasetExportOptions
- DatasetExportToOptions
- DatasetIteratorOptions
- DatasetJournalEntry
- DatasetMapper
- DatasetOptions
- DatasetReducer
- DatasetStats
- defaultRoute
- DefaultRouteUserData
- DefaultStorageIdentifier
- EnqueueLinksOptions
- EnqueueStrategy
- EnqueueStrategyOption
- EnqueueUrlsOptions
- ErrnoException
- ErrorHandler
- 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
- LauncherBrowserPoolOptions
- LauncherRemoteBrowserPoolOptions
- 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
- OwnedBrowserPool
- parseRetryAfterHeader
- parseValue
- PERSIST_STATE_KEY
- PersistenceOptions
- PersistentRateLimitError
- PlaywrightDirectNavigationOptions
- ProxyConfiguration
- ProxyConfigurationFunction
- ProxyConfigurationOptions
- purgeDefaultStorages
- PushErrorMessageOptions
- RecordOptions
- RecoverableState
- RecoverableStateOptions
- RecoverableStatePersistenceOptions
- RegExpInput
- RegExpObject
- Request
- RequestHandler
- RequestHandlerError
- RequestList
- RequestListOptions
- RequestListSourcesFunction
- RequestListState
- RequestManagerOpener
- RequestManagerTandem
- RequestOptions
- RequestQueue
- RequestQueueJournalEntry
- RequestQueueOperationInfo
- RequestQueueOperationOptions
- RequestQueueOptions
- RequestQueueStats
- RequestsLike
- RequestState
- RequestThrottledError
- RequestTransform
- RequestValidationError
- RequireContextPipeline
- 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
- StatusMessageCallback
- StatusMessageCallbackParams
- 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
- playwrightClickElements
- playwrightUtils
- AdaptivePlaywrightCrawler
- RenderingTypePredictor
- AdaptivePlaywrightCrawlerContext
- AdaptivePlaywrightCrawlerOptions
- IRenderingTypePredictor
- PlaywrightBrowserPoolOptions
- PlaywrightCrawlerOptions
- PlaywrightCrawlingContext
- PlaywrightLaunchContext
- RemotePlaywrightBrowserPoolOptions
- AdaptivePlaywrightCrawlerStatisticState
- PlaywrightBrowserPool
- PlaywrightGotoOptions
- PlaywrightHook
- RenderingType
- adaptivePlaywrightCrawlerStatisticState
- createAdaptivePlaywrightRouter
- createPlaywrightRouter
- fullResultComparator
- handleCloudflareChallengeHook
- launchPlaywright
Other
AddRequestsBatchedOptions
AddRequestsBatchedResult
ApifyLogAdapter
ArgumentValidationError
assertBrowserPoolNotConfigured
BaseCrawleeLogger
BasicCrawler
BasicCrawlerOptions
BasicCrawlingContext
BLOCKED_STATUS_CODES
BrowserCrawler
BrowserCrawlerOptions
BrowserCrawlingContext
BrowserHook
BrowserLaunchContext
CalculatedStatistics
coerceBoolean
coerceNumber
ConcurrencyConsumer
ConcurrencySystem
ConcurrencySystemOptions
ConfigField
Configuration
ConfigurationInput
ConfigurationOptions
ContextMiddleware
ContextPipeline
ContextPipelineCleanupError
ContextPipelineInitializationError
ContextPipelineInterruptedError
CpuLoadSignal
CpuLoadSignalOptions
crawleeConfigFields
CrawleeLogger
CrawleeLoggerOptions
CrawlerAddRequestsOptions
CrawlerAddRequestsResult
CrawlerRunOptions
CrawlingContext
createBasicRouter
CreateContextOptions
CreateSession
createStorageTransaction
CriticalError
Dataset
DatasetConsumer
DatasetContent
DatasetDataOptions
DatasetExportOptions
DatasetExportToOptions
DatasetIteratorOptions
DatasetJournalEntry
DatasetMapper
DatasetOptions
DatasetReducer
DatasetStats
defaultRoute
DefaultRouteUserData
DefaultStorageIdentifier
EnqueueLinksOptions
EnqueueStrategy
EnqueueStrategyOption
EnqueueUrlsOptions
ErrnoException
ErrorHandler
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
LauncherBrowserPoolOptions
LauncherRemoteBrowserPoolOptions
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
OwnedBrowserPool
parseRetryAfterHeader
parseValue
PERSIST_STATE_KEY
PersistenceOptions
PersistentRateLimitError
PlaywrightDirectNavigationOptions
ProxyConfiguration
ProxyConfigurationFunction
ProxyConfigurationOptions
purgeDefaultStorages
PushErrorMessageOptions
RecordOptions
RecoverableState
RecoverableStateOptions
RecoverableStatePersistenceOptions
RegExpInput
RegExpObject
Request
RequestHandler
RequestHandlerError
RequestList
RequestListOptions
RequestListSourcesFunction
RequestListState
RequestManagerOpener
RequestManagerTandem
RequestOptions
RequestQueue
RequestQueueJournalEntry
RequestQueueOperationInfo
RequestQueueOperationOptions
RequestQueueOptions
RequestQueueStats
RequestsLike
RequestState
RequestThrottledError
RequestTransform
RequestValidationError
RequireContextPipeline
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
StatusMessageCallback
StatusMessageCallbackParams
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
AdaptivePlaywrightCrawlerStatisticState
PlaywrightBrowserPool
A BrowserPool of Playwright browsers, as built by playwrightBrowserPool.
PlaywrightGotoOptions
PlaywrightHook
Type parameters
- UserData: Dictionary = any
RenderingType
constadaptivePlaywrightCrawlerStatisticState
The AdaptivePlaywrightCrawlerStatisticState fields as a Statistics state extension, defaults
and all. A Statistics instance to be injected into an AdaptivePlaywrightCrawler has to carry
them - deserialize.extend() your own fields onto this one and pass the result as stateExtension.
Type declaration
deserialize: ZodObject<{ browserRequestHandlerRuns: ZodDefault<ZodNumber>; httpOnlyRequestHandlerRuns: ZodDefault<ZodNumber>; renderingTypeMispredictions: ZodDefault<ZodNumber> }, $strip>
The extra statistics fields AdaptivePlaywrightCrawler tracks on top of the built-in StatisticState ones. They are available on
crawler.statistics.stateand are persisted with the rest of the statistics.