Skip to main content

PlaywrightCrawler

A web crawler that leverages the Playwright browser automation library.

The PlaywrightCrawler builds on top of the BasicCrawler, which means it inherits all of its features. On top of that it provides a high level web crawling interface on top of the Playwright library. To be more specific, it uses the Crawlee's BrowserPool to manage the Playwright's browser instances and the pages they open. You can create your own BrowserPool instance and pass it to the PlaywrightCrawler constructor, or let the crawler create a new instance with the default settings.

This crawler is ideal for crawling websites that require JavaScript execution, as it uses real browsers to download web pages and extract data. For websites that do not require JavaScript, consider using one of the HTTP client-based crawlers, such as the HttpCrawler, ParselCrawler, or BeautifulSoupCrawler. They use raw HTTP requests, which means they are much faster.

Usage

from crawlee.playwright_crawler import PlaywrightCrawler, PlaywrightCrawlingContext

crawler = PlaywrightCrawler()

# Define the default request handler, which will be called for every request.
@crawler.router.default_handler
async def request_handler(context: PlaywrightCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url} ...')

# Extract data from the page.
data = {
'url': context.request.url,
'title': await context.page.title(),
'response': (await context.response.text())[:100],
}

# Push the extracted data to the default dataset.
await context.push_data(data)

await crawler.run(['https://crawlee.dev/'])

Hierarchy

Index

Methods

__init__

  • __init__(*, browser_pool, browser_type, browser_launch_options, browser_new_context_options, headless, kwargs): None
  • A default constructor.


    Parameters

    • optionalkeyword-onlybrowser_pool: BrowserPool | None = None

      A BrowserPool instance to be used for launching the browsers and getting pages.

    • optionalkeyword-onlybrowser_type: BrowserType | None = None

      The type of browser to launch ('chromium', 'firefox', or 'webkit'). This option should not be used if browser_pool is provided.

    • optionalkeyword-onlybrowser_launch_options: Mapping[str, Any] | None = None

      Keyword arguments to pass to the browser launch method. These options are provided directly to Playwright's browser_type.launch method. For more details, refer to the Playwright

    • optionalkeyword-onlybrowser_new_context_options: Mapping[str, Any] | None = None

      Keyword arguments to pass to the browser new context method. These options are provided directly to Playwright's browser.new_context method. For more details, refer to the Playwright documentation: https://playwright.dev/python/docs/api/class-browser#browser-new-context. This option should not be used if browser_pool is provided.

    • optionalkeyword-onlyheadless: bool | None = None

      Whether to run the browser in headless mode. This option should not be used if browser_pool is provided.

    • keyword-onlyconfiguration: Configuration

      The configuration object. Some of its properties are used as defaults for the crawler.

    • keyword-onlyevent_manager: EventManager

      The event manager for managing events for the crawler and all its components.

    • keyword-onlystorage_client: BaseStorageClient

      The storage client for managing storages for the crawler and all its components.

    • keyword-onlyrequest_manager: RequestManager

      Manager of requests that should be processed by the crawler.

    • keyword-onlysession_pool: SessionPool

      A custom SessionPool instance, allowing the use of non-default configuration.

    • keyword-onlyproxy_configuration: ProxyConfiguration

      HTTP proxy configuration used when making requests.

    • keyword-onlyhttp_client: BaseHttpClient

      HTTP client used by BasicCrawlingContext.send_request method.

    • keyword-onlyrequest_handler: Callable[[TCrawlingContext], Awaitable[None]]

      A callable responsible for handling requests.

    • keyword-onlymax_request_retries: int

      Maximum number of attempts to process a single request.

    • keyword-onlymax_requests_per_crawl: int | None

      Maximum number of pages to open during a crawl. The crawl stops upon reaching this limit. Setting this value can help avoid infinite loops in misconfigured crawlers. None means no limit. Due to concurrency settings, the actual number of pages visited may slightly exceed this value.

    • keyword-onlymax_session_rotations: int

      Maximum number of session rotations per request. The crawler rotates the session if a proxy error occurs or if the website blocks the request.

    • keyword-onlymax_crawl_depth: int | None

      Specifies the maximum crawl depth. If set, the crawler will stop processing links beyond this depth. The crawl depth starts at 0 for initial requests and increases with each subsequent level of links. Requests at the maximum depth will still be processed, but no new links will be enqueued from those requests. If not set, crawling continues without depth restrictions.

    • keyword-onlyuse_session_pool: bool

      Enable the use of a session pool for managing sessions during crawling.

    • keyword-onlyretry_on_blocked: bool

      If True, the crawler attempts to bypass bot protections automatically.

    • keyword-onlyconcurrency_settings: ConcurrencySettings

      Settings to fine-tune concurrency levels.

    • keyword-onlyrequest_handler_timeout: timedelta

      Maximum duration allowed for a single request handler to run.

    • keyword-onlystatistics: Statistics[StatisticsState]

      A custom Statistics instance, allowing the use of non-default configuration.

    • keyword-onlyabort_on_error: bool

      If True, the crawler stops immediately when any request handler error occurs.

    • keyword-onlyconfigure_logging: bool

      If True, the crawler will set up logging infrastructure automatically.

    Returns None

add_requests

  • async add_requests(*, requests, batch_size, wait_time_between_batches, wait_for_all_requests_to_be_added, wait_for_all_requests_to_be_added_timeout): None
  • Add requests to the underlying request provider in batches.


    Parameters

    • optionalkeyword-onlyrequests: Sequence[str | Request]

      A list of requests to add to the queue.

    • optionalkeyword-onlybatch_size: int = 1000

      The number of requests to add in one batch.

    • optionalkeyword-onlywait_time_between_batches: timedelta = timedelta(0)

      Time to wait between adding batches.

    • optionalkeyword-onlywait_for_all_requests_to_be_added: bool = False

      If True, wait for all requests to be added before returning.

    • optionalkeyword-onlywait_for_all_requests_to_be_added_timeout: timedelta | None = None

      Timeout for waiting for all requests to be added.

    Returns None

error_handler

export_data

  • async export_data(*, path, dataset_id, dataset_name): None
  • Export data from a dataset.

    This helper method simplifies the process of exporting data from a dataset. It opens the specified dataset and then exports the data based on the provided parameters. If you need to pass options specific to the output format, use the export_data_csv or export_data_json method instead.


    Parameters

    • optionalkeyword-onlypath: str | Path

      The destination path.

    • optionalkeyword-onlydataset_id: str | None = None

      The ID of the dataset.

    • optionalkeyword-onlydataset_name: str | None = None

      The name of the dataset.

    Returns None

export_data_csv

  • async export_data_csv(*, path, dataset_id, dataset_name, dialect, delimiter, doublequote, escapechar, lineterminator, quotechar, quoting, skipinitialspace, strict): None
  • Export data from a dataset to a CSV file.

    This helper method simplifies the process of exporting data from a dataset in csv format. It opens the specified dataset and then exports the data based on the provided parameters.


    Parameters

    • optionalkeyword-onlypath: str | Path

      The destination path.

    • optionalkeyword-onlydataset_id: str | None = None

      The ID of the dataset.

    • optionalkeyword-onlydataset_name: str | None = None

      The name of the dataset.

    • keyword-onlydialect: str

      Specifies a dialect to be used in CSV parsing and writing.

    • keyword-onlydelimiter: str

      A one-character string used to separate fields. Defaults to ','.

    • keyword-onlydoublequote: bool

      Controls how instances of quotechar inside a field should be quoted. When True, the character is doubled; when False, the escapechar is used as a prefix. Defaults to True.

    • keyword-onlyescapechar: str

      A one-character string used to escape the delimiter if quoting is set to QUOTE_NONE and the quotechar if doublequote is False. Defaults to None, disabling escaping.

    • keyword-onlylineterminator: str

      The string used to terminate lines produced by the writer. Defaults to '\r\n'.

    • keyword-onlyquotechar: str

      A one-character string used to quote fields containing special characters, like the delimiter or quotechar, or fields containing new-line characters. Defaults to '"'.

    • keyword-onlyquoting: int

      Controls when quotes should be generated by the writer and recognized by the reader. Can take any of the QUOTE_* constants, with a default of QUOTE_MINIMAL.

    • keyword-onlyskipinitialspace: bool

      When True, spaces immediately following the delimiter are ignored. Defaults to False.

    • keyword-onlystrict: bool

      When True, raises an exception on bad CSV input. Defaults to False.

    Returns None

export_data_json

  • async export_data_json(*, path, dataset_id, dataset_name, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys): None
  • Export data from a dataset to a JSON file.

    This helper method simplifies the process of exporting data from a dataset in json format. It opens the specified dataset and then exports the data based on the provided parameters.


    Parameters

    • optionalkeyword-onlypath: str | Path

      The destination path

    • optionalkeyword-onlydataset_id: str | None = None

      The ID of the dataset.

    • optionalkeyword-onlydataset_name: str | None = None

      The name of the dataset.

    • keyword-onlyskipkeys: bool

      If True (default: False), dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

    • keyword-onlyensure_ascii: bool

      Determines if non-ASCII characters should be escaped in the output JSON string.

    • keyword-onlycheck_circular: bool

      If False (default: True), skips the circular reference check for container types. A circular reference will result in a RecursionError or worse if unchecked.

    • keyword-onlyallow_nan: bool

      If False (default: True), raises a ValueError for out-of-range float values (nan, inf, -inf) to strictly comply with the JSON specification. If True, uses their JavaScript equivalents (NaN, Infinity, -Infinity).

    • keyword-onlycls: type[json.JSONEncoder]

      Allows specifying a custom JSON encoder.

    • keyword-onlyindent: int

      Specifies the number of spaces for indentation in the pretty-printed JSON output.

    • keyword-onlyseparators: tuple[str, str]

      A tuple of (item_separator, key_separator). The default is (', ', ': ') if indent is None and (',', ': ') otherwise.

    • keyword-onlydefault: Callable

      A function called for objects that can't be serialized otherwise. It should return a JSON-encodable version of the object or raise a TypeError.

    • keyword-onlysort_keys: bool

      Specifies whether the output JSON object should have keys sorted alphabetically.

    Returns None

failed_request_handler

get_data

  • async get_data(*, dataset_id, dataset_name, offset, limit, clean, desc, fields, omit, unwind, skip_empty, skip_hidden, flatten, view): DatasetItemsListPage
  • Retrieve data from a dataset.

    This helper method simplifies the process of retrieving data from a dataset. It opens the specified dataset and then retrieves the data based on the provided parameters.


    Parameters

    • optionalkeyword-onlydataset_id: str | None = None

      The ID of the dataset.

    • optionalkeyword-onlydataset_name: str | None = None

      The name of the dataset.

    • keyword-onlyoffset: int

      Skips the specified number of items at the start.

    • keyword-onlylimit: int

      The maximum number of items to retrieve. Unlimited if None.

    • keyword-onlyclean: bool

      Returns only non-empty items and excludes hidden fields. Shortcut for skip_hidden and skip_empty.

    • keyword-onlydesc: bool

      Set to True to sort results in descending order.

    • keyword-onlyfields: list[str]

      Fields to include in each item. Sorts fields as specified if provided.

    • keyword-onlyomit: list[str]

      Fields to exclude from each item.

    • keyword-onlyunwind: str

      Unwinds items by a specified array field, turning each element into a separate item.

    • keyword-onlyskip_empty: bool

      Excludes empty items from the results if True.

    • keyword-onlyskip_hidden: bool

      Excludes fields starting with '#' if True.

    • keyword-onlyflatten: list[str]

      Fields to be flattened in returned items.

    • keyword-onlyview: str

      Specifies the dataset view to be used.

    Returns DatasetItemsListPage

get_dataset

  • async get_dataset(*, id, name): Dataset
  • Return the dataset with the given ID or name. If none is provided, return the default dataset.


    Parameters

    • optionalkeyword-onlyid: str | None = None
    • optionalkeyword-onlyname: str | None = None

    Returns Dataset

get_key_value_store

  • Return the key-value store with the given ID or name. If none is provided, return the default KVS.


    Parameters

    • optionalkeyword-onlyid: str | None = None
    • optionalkeyword-onlyname: str | None = None

    Returns KeyValueStore

get_request_manager

  • Return the configured request provider. If none is configured, open and return the default request queue.


    Returns RequestManager

pre_navigation_hook

  • pre_navigation_hook(*, hook): None
  • Register a hook to be called before each navigation.


    Parameters

    • optionalkeyword-onlyhook: Callable[[PlaywrightPreNavCrawlingContext], Awaitable[None]]

      A coroutine function to be called before each navigation.

    Returns None

run

  • Run the crawler until all requests are processed.


    Parameters

    • optionalkeyword-onlyrequests: Sequence[str | Request] | None = None

      The requests to be enqueued before the crawler starts.

    • optionalkeyword-onlypurge_request_queue: bool = True

      If this is True and the crawler is not being run for the first time, the default request queue will be purged.

    Returns FinalStatistics

stop

  • stop(*, reason): None
  • Set flag to stop crawler.

    This stops current crawler run regardless of whether all requests were finished.


    Parameters

    • optionalkeyword-onlyreason: str = 'Stop was called externally.'

      Reason for stopping that will be used in logs.

    Returns None

Properties

log

log: logging.Logger

The logger used by the crawler.

router

The router used to handle each individual crawling request.

statistics

Statistics about the current (or last) crawler run.