同步完整源码 - 2026-05-24
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
---
|
||||
id: apify-platform
|
||||
title: Apify platform
|
||||
description: Apify platform - large-scale and high-performance web scraping
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
|
||||
import LogWithConfigExample from '!!raw-loader!./code_examples/apify/log_with_config_example.py';
|
||||
import CrawlerAsActorExample from '!!raw-loader!./code_examples/apify/crawler_as_actor_example.py';
|
||||
import ProxyExample from '!!raw-loader!./code_examples/apify/proxy_example.py';
|
||||
import ProxyAdvancedExample from '!!raw-loader!./code_examples/apify/proxy_advanced_example.py';
|
||||
|
||||
Apify is a [platform](https://apify.com) built to serve large-scale and high-performance web scraping and automation needs. It provides easy access to [compute instances (Actors)](#what-is-an-actor), convenient request and result storages, [proxies](../guides/proxy-management), scheduling, webhooks and [more](https://docs.apify.com/), accessible through a [web interface](https://console.apify.com) or an [API](https://docs.apify.com/api).
|
||||
|
||||
While we think that the Apify platform is super cool, and it's definitely worth signing up for a [free account](https://console.apify.com/sign-up), **Crawlee is and will always be open source**, runnable locally or on any cloud infrastructure.
|
||||
|
||||
:::note
|
||||
|
||||
We do not test Crawlee in other cloud environments such as Lambda or on specific architectures such as Raspberry PI. We strive to make it work, but there are no guarantees.
|
||||
|
||||
:::
|
||||
|
||||
## Requirements
|
||||
|
||||
To run your Crawlee code on Apify platform, you need an Apify account. If you don't have one yet, you can sign up [here](https://console.apify.com/sign-up).
|
||||
|
||||
Additionally, you must have the [Apify CLI](https://docs.apify.com/cli/) installed on your computer. For installation instructions, refer to the [Installation guide](https://docs.apify.com/cli/docs/installation).
|
||||
|
||||
Finally, ensure that the [Apify SDK] (https://docs.apify.com/sdk/python/) is installed in your project. You can install it using `pip`:
|
||||
|
||||
```bash
|
||||
pip install apify
|
||||
```
|
||||
|
||||
## Logging into Apify platform from Crawlee
|
||||
|
||||
To access your [Apify account](https://console.apify.com/sign-up) from Crawlee, you must provide credentials - your [API token](https://console.apify.com/account?tab=integrations). You can do that either by utilizing [Apify CLI](https://docs.apify.com/cli/) or with environment variables.
|
||||
|
||||
Once you provide credentials to your Apify CLI installation, you will be able to use all the Apify platform features, such as calling Actors, saving to cloud storages, using Apify proxies, setting up webhooks and so on.
|
||||
|
||||
### Log in with CLI
|
||||
|
||||
Apify CLI allows you to log in to your Apify account on your computer. If you then run your crawler using the CLI, your credentials will automatically be added.
|
||||
|
||||
```bash
|
||||
npm install -g apify-cli
|
||||
apify login -t YOUR_API_TOKEN
|
||||
```
|
||||
|
||||
### Log in with environment variables
|
||||
|
||||
Alternatively, you can always provide credentials to your Actor by setting the [`APIFY_TOKEN`](#apify_token) environment variable to your API token.
|
||||
|
||||
> There's also the [`APIFY_PROXY_PASSWORD`](#apify_proxy_password)
|
||||
> environment variable. Actor automatically infers that from your token, but it can be useful
|
||||
> when you need to access proxies from a different account than your token represents.
|
||||
|
||||
### Log in with Configuration
|
||||
|
||||
Another option is to use the [`Configuration`](https://docs.apify.com/sdk/python/reference/class/Configuration) instance and set your api token there.
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{LogWithConfigExample}
|
||||
</CodeBlock>
|
||||
|
||||
## What is an Actor
|
||||
|
||||
When you deploy your script to the Apify platform, it becomes an [Actor](https://apify.com/actors). An Actor is a serverless microservice that accepts an input and produces an output. It can run for a few seconds, hours or even infinitely. An Actor can perform anything from a simple action such as filling out a web form or sending an email, to complex operations such as crawling an entire website and removing duplicates from a large dataset.
|
||||
|
||||
Actors can be shared in the [Apify Store](https://apify.com/store) so that other people can use them. But don't worry, if you share your Actor in the store and somebody uses it, it runs under their account, not yours.
|
||||
|
||||
**Related links**
|
||||
|
||||
- [Store of existing Actors](https://apify.com/store)
|
||||
- [Documentation](https://docs.apify.com/actors)
|
||||
- [View Actors in Apify Console](https://console.apify.com/actors)
|
||||
- [API reference](https://apify.com/docs/api/v2#/reference/actors)
|
||||
|
||||
## Running an Actor locally
|
||||
|
||||
First let's create a boilerplate of the new Actor. You could use Apify CLI and just run:
|
||||
|
||||
```bash
|
||||
apify create my-hello-world
|
||||
```
|
||||
|
||||
The CLI will prompt you to select a project boilerplate template - let's pick "Crawlee + BeautifulSoup". The tool will create a directory called `my-hello-world` with Python project files. You can run the Actor as follows:
|
||||
|
||||
```bash
|
||||
cd my-hello-world
|
||||
apify run
|
||||
```
|
||||
|
||||
## Running Crawlee code as an Actor
|
||||
|
||||
For running Crawlee code as an Actor on [Apify platform](https://apify.com/actors) you need to wrap the body of the main function of your crawler with `async with Actor`.
|
||||
|
||||
:::info NOTE
|
||||
Adding `async with Actor` is the only important thing needed to run it on Apify platform as an Actor. It is needed to initialize your Actor (e.g. to set the correct storage implementation) and to correctly handle exiting the process.
|
||||
:::
|
||||
|
||||
Let's look at the `BeautifulSoupCrawler` example from the [Quick start](../quick-start) guide:
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{CrawlerAsActorExample}
|
||||
</CodeBlock>
|
||||
|
||||
Note that you could also run your Actor (that is using Crawlee) locally with Apify CLI. You could start it via the following command in your project folder:
|
||||
|
||||
```bash
|
||||
apify run
|
||||
```
|
||||
|
||||
## Deploying an Actor to Apify platform
|
||||
|
||||
Now (assuming you are already logged in to your Apify account) you can easily deploy your code to the Apify platform by running:
|
||||
|
||||
```bash
|
||||
apify push
|
||||
```
|
||||
|
||||
Your script will be uploaded to and built on the Apify platform so that it can be run there. For more information, view the
|
||||
[Apify Actor](https://docs.apify.com/cli) documentation.
|
||||
|
||||
## Usage on Apify platform
|
||||
|
||||
You can also develop your Actor in an online code editor directly on the platform (you'll need an Apify Account). Let's go to the [Actors](https://console.apify.com/actors) page in the app, click *Create new* and then go to the *Source* tab and start writing the code or paste one of the examples from the [Examples](../examples) section.
|
||||
|
||||
## Storages
|
||||
|
||||
There are several things worth mentioning here.
|
||||
|
||||
### Helper functions for default Key-Value Store and Dataset
|
||||
|
||||
To simplify access to the _default_ storages, instead of using the helper functions of respective storage classes, you could use:
|
||||
- [`Actor.set_value()`](https://docs.apify.com/sdk/python/reference/class/Actor#set_value), [`Actor.get_value()`](https://docs.apify.com/sdk/python/reference/class/Actor#get_value), [`Actor.get_input()`](https://docs.apify.com/sdk/python/reference/class/Actor#get_input) for [`Key-Value Store`](https://docs.apify.com/sdk/python/reference/class/KeyValueStore)
|
||||
- [`Actor.push_data()`](https://docs.apify.com/sdk/python/reference/class/Actor#push_data) for [`Dataset`](https://docs.apify.com/sdk/python/reference/class/Dataset)
|
||||
|
||||
### Using platform storage in a local Actor
|
||||
|
||||
When you plan to use the platform storage while developing and running your Actor locally, you should use [`Actor.open_key_value_store()`](https://docs.apify.com/sdk/python/reference/class/Actor#open_key_value_store), [`Actor.open_dataset()`](https://docs.apify.com/sdk/python/reference/class/Actor#open_dataset) and [`Actor.open_request_queue()`](https://docs.apify.com/sdk/python/reference/class/Actor#open_request_queue) to open the respective storage.
|
||||
|
||||
Using each of these methods allows to pass the `force_cloud` keyword argument. If set to `True`, cloud storage will be used instead of the folder on the local disk.
|
||||
|
||||
:::note
|
||||
If you don't plan to force usage of the platform storages when running the Actor locally, there is no need to use the [`Actor`](https://docs.apify.com/sdk/python/reference/class/Actor) class for it. The Crawlee variants <ApiLink to="class/KeyValueStore#open">`KeyValueStore.open()`</ApiLink>, <ApiLink to="class/Dataset#open">`Dataset.open()`</ApiLink> and <ApiLink to="class/RequestQueue#open">`RequestQueue.open()`</ApiLink> will work the same.
|
||||
:::
|
||||
|
||||
{/*
|
||||
### Getting public url of an item in the platform storage
|
||||
|
||||
If you need to share a link to some file stored in a [Key-Value](https://docs.apify.com/sdk/python/reference/class/KeyValueStore) Store on Apify platform, you can use [`get_public_url()`](https://docs.apify.com/sdk/python/reference/class/KeyValueStore#get_public_url) method. It accepts only one parameter: `key` - the key of the item you want to share.
|
||||
|
||||
<CodeBlock language="python">
|
||||
{GetPublicUrlSource}
|
||||
</CodeBlock>
|
||||
|
||||
*/}
|
||||
|
||||
### Exporting dataset data
|
||||
|
||||
When the <ApiLink to="class/Dataset">`Dataset`</ApiLink> is stored on the [Apify platform](https://apify.com/actors), you can export its data to the following formats: HTML, JSON, CSV, Excel, XML and RSS. The datasets are displayed on the Actor run details page and in the [Storage](https://console.apify.com/storage) section in the Apify Console. The actual data is exported using the [Get dataset items](https://apify.com/docs/api/v2#/reference/datasets/item-collection/get-items) Apify API endpoint. This way you can easily share the crawling results.
|
||||
|
||||
**Related links**
|
||||
|
||||
- [Apify platform storage documentation](https://docs.apify.com/storage)
|
||||
- [View storage in Apify Console](https://console.apify.com/storage)
|
||||
- [Key-value stores API reference](https://apify.com/docs/api/v2#/reference/key-value-stores)
|
||||
- [Datasets API reference](https://docs.apify.com/api/v2#/reference/datasets)
|
||||
- [Request queues API reference](https://docs.apify.com/api/v2#/reference/request-queues)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The following describes select environment variables set by the Apify platform. For a complete list, see the [Environment variables](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables) section in the Apify platform documentation.
|
||||
|
||||
:::note
|
||||
|
||||
It's important to notice that `CRAWLEE_` environment variables don't need to be replaced with equivalent `APIFY_` ones. Likewise, Crawlee understands `APIFY_` environment variables.
|
||||
|
||||
:::
|
||||
|
||||
### `APIFY_TOKEN`
|
||||
|
||||
The API token for your Apify account. It is used to access the Apify API, e.g. to access cloud storage
|
||||
or to run an Actor on the Apify platform. You can find your API token on the
|
||||
[Account Settings / Integrations](https://console.apify.com/account?tab=integrations) page.
|
||||
|
||||
### Combinations of `APIFY_TOKEN` and `CRAWLEE_STORAGE_DIR`
|
||||
|
||||
By combining the env vars in various ways, you can greatly influence the Actor's behavior.
|
||||
|
||||
| Env Vars | API | Storages |
|
||||
| --------------------------------------- | --- | ---------------- |
|
||||
| none OR `CRAWLEE_STORAGE_DIR` | no | local |
|
||||
| `APIFY_TOKEN` | yes | Apify platform |
|
||||
| `APIFY_TOKEN` AND `CRAWLEE_STORAGE_DIR` | yes | local + platform |
|
||||
|
||||
When using both `APIFY_TOKEN` and `CRAWLEE_STORAGE_DIR`, you can use all the Apify platform
|
||||
features and your data will be stored locally by default. If you want to access platform storages,
|
||||
you can use the `force_cloud=true` option in their respective functions.
|
||||
|
||||
### `APIFY_PROXY_PASSWORD`
|
||||
|
||||
Optional password to [Apify Proxy](https://docs.apify.com/proxy) for IP address rotation.
|
||||
Assuming Apify Account was already created, you can find the password on the [Proxy page](https://console.apify.com/proxy)
|
||||
in the Apify Console. The password is automatically inferred using the `APIFY_TOKEN` env var,
|
||||
so in most cases, you don't need to touch it. You should use it when, for some reason,
|
||||
you need access to Apify Proxy, but not access to Apify API, or when you need access to
|
||||
proxy from a different account than your token represents.
|
||||
|
||||
## Proxy management
|
||||
|
||||
In addition to your own proxy servers and proxy servers acquired from
|
||||
third-party providers used together with Crawlee, you can also rely on [Apify Proxy](https://apify.com/proxy)
|
||||
for your scraping needs.
|
||||
|
||||
### Apify proxy
|
||||
|
||||
If you are already subscribed to Apify Proxy, you can start using them immediately in only a few lines of code (for local usage you first should be [logged in](#logging-into-apify-platform-from-crawlee) to your Apify account.
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{ProxyExample}
|
||||
</CodeBlock>
|
||||
|
||||
Note that unlike using your own proxies in Crawlee, you shouldn't use the constructor to create <ApiLink to="class/ProxyConfiguration">`ProxyConfiguration`</ApiLink> instances. For using the Apify Proxy you should create an instance using the [`Actor.create_proxy_configuration()`](https://docs.apify.com/sdk/python/reference/class/Actor#create_proxy_configuration) function instead.
|
||||
|
||||
### Advanced Apify proxy configuration
|
||||
|
||||
With Apify Proxy, you can select specific proxy groups to use, or countries to connect from.
|
||||
This allows you to get better proxy performance after some initial research.
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{ProxyAdvancedExample}
|
||||
</CodeBlock>
|
||||
|
||||
Now your crawlers will use only Residential proxies from the US. Note that you must first get access
|
||||
to a proxy group before you are able to use it. You can check proxy groups available to you
|
||||
in the [proxy dashboard](https://console.apify.com/proxy).
|
||||
|
||||
### Apify proxy vs. own proxies
|
||||
|
||||
The [`ProxyConfiguration`](https://docs.apify.com/sdk/python/reference/class/ProxyConfiguration) class covers both Apify Proxy and custom proxy URLs so that you can easily switch between proxy providers. However, some features of the class are available only to Apify Proxy users, mainly because Apify Proxy is what one would call a super-proxy. It's not a single proxy server, but an API endpoint that allows connection through millions of different IP addresses. So the class essentially has two modes: Apify Proxy or Own (third party) proxy.
|
||||
|
||||
The difference is easy to remember.
|
||||
- If you're using your own proxies - you should create a <ApiLink to="class/ProxyConfiguration">`ProxyConfiguration`</ApiLink> instance directly.
|
||||
- If you are planning to use Apify Proxy - you should create an instance using the [`Actor.create_proxy_configuration()`](https://docs.apify.com/sdk/python/reference/class/Actor#create_proxy_configuration) function. The `new_url_function` parameter enables the use of your custom proxy URLs, whereas all the other options are there to configure Apify Proxy.
|
||||
|
||||
**Related links**
|
||||
|
||||
- [Apify Proxy docs](https://docs.apify.com/proxy)
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
id: aws-lambda
|
||||
title: Deploy on AWS Lambda
|
||||
description: Prepare your crawler to run on AWS Lambda.
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
|
||||
import BeautifulSoupCrawlerLambda from '!!raw-loader!./code_examples/aws/beautifulsoup_crawler_lambda.py';
|
||||
import PlaywrightCrawlerLambda from '!!raw-loader!./code_examples/aws/playwright_crawler_lambda.py';
|
||||
import PlaywrightCrawlerDockerfile from '!!raw-loader!./code_examples/aws/playwright_dockerfile';
|
||||
|
||||
[AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) is a serverless compute service that lets you run code without provisioning or managing servers. This guide covers deploying <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink> and <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink>.
|
||||
|
||||
The code examples are based on the [BeautifulSoupCrawler example](../examples/beautifulsoup-crawler).
|
||||
|
||||
## BeautifulSoupCrawler on AWS Lambda
|
||||
|
||||
For simple crawlers that don't require browser rendering, you can deploy using a ZIP archive.
|
||||
|
||||
### Updating the code
|
||||
|
||||
When instantiating a crawler, use <ApiLink to="class/MemoryStorageClient">`MemoryStorageClient`</ApiLink>. By default, Crawlee uses file-based storage, but the Lambda filesystem is read-only (except for `/tmp`). Using `MemoryStorageClient` tells Crawlee to use in-memory storage instead.
|
||||
|
||||
Wrap the crawler logic in a `lambda_handler` function. This is the entry point that AWS will execute.
|
||||
|
||||
:::important
|
||||
|
||||
Make sure to always instantiate a new crawler for every Lambda invocation. AWS keeps the environment running for some time after the first execution (to reduce cold-start times), so subsequent calls may access an already-used crawler instance.
|
||||
|
||||
**TL;DR: Keep your Lambda stateless.**
|
||||
|
||||
:::
|
||||
|
||||
Finally, return the scraped data from the Lambda when the crawler run ends.
|
||||
|
||||
<CodeBlock language="python" title="lambda_function.py">
|
||||
{BeautifulSoupCrawlerLambda}
|
||||
</CodeBlock>
|
||||
|
||||
### Preparing the environment
|
||||
|
||||
Lambda requires all dependencies to be included in the deployment package. Create a virtual environment and install dependencies:
|
||||
|
||||
```bash
|
||||
python3.14 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install 'crawlee[beautifulsoup]' 'boto3' 'aws-lambda-powertools'
|
||||
```
|
||||
|
||||
[`boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) is the AWS SDK for Python. Including it in your dependencies is recommended to avoid version misalignment issues with the Lambda runtime.
|
||||
|
||||
### Creating the ZIP archive
|
||||
|
||||
Create a ZIP archive from your project, including dependencies from the virtual environment:
|
||||
|
||||
```bash
|
||||
cd .venv/lib/python3.14/site-packages
|
||||
zip -r ../../../../package.zip .
|
||||
cd ../../../../
|
||||
zip package.zip lambda_function.py
|
||||
```
|
||||
|
||||
:::note Large dependencies?
|
||||
|
||||
AWS has a limit of 50 MB for direct upload and 250 MB for unzipped deployment package size.
|
||||
|
||||
A better way to manage dependencies is by using Lambda Layers. With Layers, you can share files between multiple Lambda functions and keep the actual code as slim as possible.
|
||||
|
||||
To create a Lambda Layer:
|
||||
|
||||
1. Create a `python/` folder and copy dependencies from `site-packages` into it
|
||||
2. Create a zip archive: `zip -r layer.zip python/`
|
||||
3. Create a new Lambda Layer from the archive (you may need to upload it to S3 first)
|
||||
4. Attach the Layer to your Lambda function
|
||||
|
||||
:::
|
||||
|
||||
### Creating the Lambda function
|
||||
|
||||
Create the Lambda function in the AWS Lambda Console:
|
||||
|
||||
1. Navigate to `Lambda` in [AWS Management Console](https://aws.amazon.com/console/).
|
||||
2. Click **Create function**.
|
||||
3. Select **Author from scratch**.
|
||||
4. Enter a **Function name**, for example `BeautifulSoupTest`.
|
||||
5. Choose a **Python runtime** that matches the version used in your virtual environment (for example, Python 3.14).
|
||||
6. Click **Create function** to finish.
|
||||
|
||||
Once created, upload `package.zip` as the code source in the AWS Lambda Console using the "Upload from" button.
|
||||
|
||||
In Lambda Runtime Settings, set the handler. Since the file is named `lambda_function.py` and the function is `lambda_handler`, you can use the default value `lambda_function.lambda_handler`.
|
||||
|
||||
:::tip Configuration
|
||||
|
||||
In the Configuration tab, you can adjust:
|
||||
|
||||
- **Memory**: Memory size can greatly affect execution speed. A minimum of 256-512 MB is recommended.
|
||||
- **Timeout**: Set according to the size of the website you are scraping (1 minute for the example code).
|
||||
- **Ephemeral storage**: Size of the `/tmp` directory.
|
||||
|
||||
See the [official documentation](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) to learn how performance and cost scale with memory.
|
||||
|
||||
:::
|
||||
|
||||
After the Lambda deploys, you can test it by clicking the "Test" button. The event contents don't matter for a basic test, but you can parameterize your crawler by parsing the event object that AWS passes as the first argument to the handler.
|
||||
|
||||
## PlaywrightCrawler on AWS Lambda
|
||||
|
||||
For crawlers that require browser rendering, you need to deploy using Docker container images because Playwright and browser binaries exceed Lambda's ZIP deployment size limits.
|
||||
|
||||
### Updating the code
|
||||
|
||||
As with <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>, use <ApiLink to="class/MemoryStorageClient">`MemoryStorageClient`</ApiLink> and wrap the logic in a `lambda_handler` function. Additionally, configure `browser_launch_options` with flags optimized for serverless environments. These flags disable sandboxing and GPU features that aren't available in Lambda's containerized runtime.
|
||||
|
||||
<CodeBlock language="python" title="main.py">
|
||||
{PlaywrightCrawlerLambda}
|
||||
</CodeBlock>
|
||||
|
||||
### Installing and configuring AWS CLI
|
||||
|
||||
Install AWS CLI following the [official documentation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) according to your operating system.
|
||||
|
||||
Authenticate by running:
|
||||
|
||||
```bash
|
||||
aws login
|
||||
```
|
||||
|
||||
### Preparing the project
|
||||
|
||||
Initialize the project by running `uvx 'crawlee[cli]' create`.
|
||||
|
||||
Or use a single command if you don't need interactive mode:
|
||||
|
||||
```bash
|
||||
uvx 'crawlee[cli]' create aws_playwright --crawler-type playwright --http-client impit --package-manager uv --no-apify --start-url 'https://crawlee.dev' --install
|
||||
```
|
||||
|
||||
Add the following dependencies:
|
||||
|
||||
```bash
|
||||
uv add awslambdaric aws-lambda-powertools boto3
|
||||
```
|
||||
|
||||
[`boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) is the AWS SDK for Python. Use it if your function integrates with any other AWS services.
|
||||
|
||||
The project is created with a Dockerfile that needs to be modified for AWS Lambda by adding `ENTRYPOINT` and updating `CMD`:
|
||||
|
||||
<CodeBlock language="dockerfile" title="Dockerfile">
|
||||
{PlaywrightCrawlerDockerfile}
|
||||
</CodeBlock>
|
||||
|
||||
### Building and pushing the Docker image
|
||||
|
||||
Create a repository `lambda/aws-playwright` in [Amazon Elastic Container Registry](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) in the same region where your Lambda functions will run. To learn more, refer to the [official documentation](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-cli.html).
|
||||
|
||||
Navigate to the created repository and click the "View push commands" button. This will open a window with console commands for uploading the Docker image to your repository. Execute them.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin {user-specific-data}
|
||||
docker build --platform linux/amd64 --provenance=false -t lambda/aws-playwright .
|
||||
docker tag lambda/aws-playwright:latest {user-specific-data}/lambda/aws-playwright:latest
|
||||
docker push {user-specific-data}/lambda/aws-playwright:latest
|
||||
```
|
||||
|
||||
### Creating the Lambda function
|
||||
|
||||
1. Navigate to `Lambda` in [AWS Management Console](https://aws.amazon.com/console/).
|
||||
2. Click **Create function**.
|
||||
3. Select **Container image**.
|
||||
4. Browse and select your ECR image.
|
||||
5. Click **Create function** to finish.
|
||||
|
||||
:::tip Configuration
|
||||
|
||||
In the Configuration tab, you can adjust resources. Playwright crawlers require more resources than BeautifulSoup crawlers:
|
||||
|
||||
- **Memory**: Minimum 1024 MB recommended. Browser operations are memory-intensive, so 2048 MB or more may be needed for complex pages.
|
||||
- **Timeout**: Set according to crawl size. Browser startup adds overhead, so allow at least 5 minutes even for simple crawls.
|
||||
- **Ephemeral storage**: Default 512 MB is usually sufficient unless downloading large files.
|
||||
|
||||
See the [official documentation](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) to learn how performance and cost scale with memory.
|
||||
|
||||
:::
|
||||
|
||||
After the Lambda deploys, click the "Test" button to invoke it. The event contents don't matter for a basic test, but you can parameterize your crawler by parsing the event object that AWS passes as the first argument to the handler.
|
||||
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
|
||||
from apify import Actor
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Wrap the crawler code in an Actor context manager.
|
||||
async with Actor:
|
||||
crawler = BeautifulSoupCrawler(max_requests_per_crawl=10)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
}
|
||||
await context.push_data(data)
|
||||
await context.enqueue_links()
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,16 @@
|
||||
import asyncio
|
||||
|
||||
from apify import Actor
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with Actor:
|
||||
store = await Actor.open_key_value_store()
|
||||
await store.set_value('your-file', {'foo': 'bar'})
|
||||
url = store.get_public_url('your-file')
|
||||
Actor.log.info(f'KVS public URL: {url}')
|
||||
# https://api.apify.com/v2/key-value-stores/<your-store-id>/records/your-file
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,19 @@
|
||||
import asyncio
|
||||
|
||||
from apify import Actor, Configuration
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create a new configuration with your API key. You can find it at
|
||||
# https://console.apify.com/settings/integrations. It can be provided either
|
||||
# as a parameter "token" or as an environment variable "APIFY_TOKEN".
|
||||
config = Configuration(
|
||||
token='apify_api_YOUR_TOKEN',
|
||||
)
|
||||
|
||||
async with Actor(config):
|
||||
Actor.log.info('Hello from Apify platform!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,20 @@
|
||||
import asyncio
|
||||
|
||||
from apify import Actor
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with Actor:
|
||||
proxy_configuration = await Actor.create_proxy_configuration(
|
||||
password='apify_proxy_YOUR_PASSWORD',
|
||||
# Specify the proxy group to use.
|
||||
groups=['RESIDENTIAL'],
|
||||
# Set the country code for the proxy.
|
||||
country_code='US',
|
||||
)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,24 @@
|
||||
import asyncio
|
||||
|
||||
from apify import Actor
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with Actor:
|
||||
# Create a new Apify Proxy configuration. The password can be found at
|
||||
# https://console.apify.com/proxy/http-settings and should be provided either
|
||||
# as a parameter "password" or as an environment variable "APIFY_PROXY_PASSWORD".
|
||||
proxy_configuration = await Actor.create_proxy_configuration(
|
||||
password='apify_proxy_YOUR_PASSWORD',
|
||||
)
|
||||
|
||||
if not proxy_configuration:
|
||||
Actor.log.warning('Failed to create proxy configuration.')
|
||||
return
|
||||
|
||||
proxy_url = await proxy_configuration.new_url()
|
||||
Actor.log.info(f'Proxy URL: {proxy_url}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
from crawlee.storage_clients import MemoryStorageClient
|
||||
from crawlee.storages import Dataset, RequestQueue
|
||||
|
||||
|
||||
async def main() -> str:
|
||||
# highlight-start
|
||||
# Disable writing storage data to the file system
|
||||
storage_client = MemoryStorageClient()
|
||||
# highlight-end
|
||||
|
||||
# Initialize storages
|
||||
dataset = await Dataset.open(storage_client=storage_client)
|
||||
request_queue = await RequestQueue.open(storage_client=storage_client)
|
||||
|
||||
crawler = BeautifulSoupCrawler(
|
||||
storage_client=storage_client,
|
||||
max_request_retries=1,
|
||||
request_handler_timeout=timedelta(seconds=30),
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
'h1s': [h1.text for h1 in context.soup.find_all('h1')],
|
||||
'h2s': [h2.text for h2 in context.soup.find_all('h2')],
|
||||
'h3s': [h3.text for h3 in context.soup.find_all('h3')],
|
||||
}
|
||||
|
||||
await context.push_data(data)
|
||||
await context.enqueue_links()
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
# Extract data saved in `Dataset`
|
||||
data = await crawler.get_data()
|
||||
|
||||
# Clean up storages after the crawl
|
||||
await dataset.drop()
|
||||
await request_queue.drop()
|
||||
|
||||
# Serialize the list of scraped items to JSON string
|
||||
return json.dumps(data.items)
|
||||
|
||||
|
||||
def lambda_handler(_event: dict[str, Any], _context: LambdaContext) -> dict[str, Any]:
|
||||
result = asyncio.run(main())
|
||||
# Return the response with results
|
||||
return {'statusCode': 200, 'body': result}
|
||||
@@ -0,0 +1,73 @@
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.storage_clients import MemoryStorageClient
|
||||
from crawlee.storages import Dataset, RequestQueue
|
||||
|
||||
|
||||
async def main() -> str:
|
||||
# highlight-start
|
||||
# Disable writing storage data to the file system
|
||||
storage_client = MemoryStorageClient()
|
||||
# highlight-end
|
||||
|
||||
# Initialize storages
|
||||
dataset = await Dataset.open(storage_client=storage_client)
|
||||
request_queue = await RequestQueue.open(storage_client=storage_client)
|
||||
|
||||
crawler = PlaywrightCrawler(
|
||||
storage_client=storage_client,
|
||||
max_request_retries=1,
|
||||
request_handler_timeout=timedelta(seconds=30),
|
||||
max_requests_per_crawl=10,
|
||||
# highlight-start
|
||||
# Configure Playwright to run in AWS Lambda environment
|
||||
browser_launch_options={
|
||||
'args': [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-gpu',
|
||||
'--single-process',
|
||||
]
|
||||
},
|
||||
# highlight-end
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': await context.page.title(),
|
||||
'h1s': await context.page.locator('h1').all_text_contents(),
|
||||
'h2s': await context.page.locator('h2').all_text_contents(),
|
||||
'h3s': await context.page.locator('h3').all_text_contents(),
|
||||
}
|
||||
|
||||
await context.push_data(data)
|
||||
await context.enqueue_links()
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
# Extract data saved in `Dataset`
|
||||
data = await crawler.get_data()
|
||||
|
||||
# Clean up storages after the crawl
|
||||
await dataset.drop()
|
||||
await request_queue.drop()
|
||||
|
||||
# Serialize the list of scraped items to JSON string
|
||||
return json.dumps(data.items)
|
||||
|
||||
|
||||
def lambda_handler(_event: dict[str, Any], _context: LambdaContext) -> dict[str, Any]:
|
||||
result = asyncio.run(main())
|
||||
# Return the response with results
|
||||
return {'statusCode': 200, 'body': result}
|
||||
@@ -0,0 +1,36 @@
|
||||
FROM apify/actor-python-playwright:3.14
|
||||
|
||||
RUN apt update && apt install -yq git && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install -U pip setuptools \
|
||||
&& pip install 'uv<1'
|
||||
|
||||
ENV UV_PROJECT_ENVIRONMENT="/usr/local"
|
||||
|
||||
COPY pyproject.toml uv.lock ./
|
||||
|
||||
RUN echo "Python version:" \
|
||||
&& python --version \
|
||||
&& echo "Installing dependencies:" \
|
||||
&& PLAYWRIGHT_INSTALLED=$(pip freeze | grep -q playwright && echo "true" || echo "false") \
|
||||
&& if [ "$PLAYWRIGHT_INSTALLED" = "true" ]; then \
|
||||
echo "Playwright already installed, excluding from uv sync" \
|
||||
&& uv sync --frozen --no-install-project --no-editable -q --no-dev --inexact --no-install-package playwright; \
|
||||
else \
|
||||
echo "Playwright not found, installing all dependencies" \
|
||||
&& uv sync --frozen --no-install-project --no-editable -q --no-dev --inexact; \
|
||||
fi \
|
||||
&& echo "All installed Python packages:" \
|
||||
&& pip freeze
|
||||
|
||||
COPY . ./
|
||||
|
||||
RUN python -m compileall -q .
|
||||
|
||||
# highlight-start
|
||||
# AWS Lambda entrypoint
|
||||
ENTRYPOINT [ "/usr/local/bin/python3", "-m", "awslambdaric" ]
|
||||
|
||||
# Lambda handler function
|
||||
CMD [ "aws_playwright.main.lambda_handler" ]
|
||||
# highlight-end
|
||||
@@ -0,0 +1,53 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
from litestar import Litestar, get
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.storage_clients import MemoryStorageClient
|
||||
|
||||
|
||||
@get('/')
|
||||
async def main() -> str:
|
||||
"""The crawler entry point that will be called when the HTTP endpoint is accessed."""
|
||||
# highlight-start
|
||||
# Disable writing storage data to the file system
|
||||
storage_client = MemoryStorageClient()
|
||||
# highlight-end
|
||||
|
||||
crawler = PlaywrightCrawler(
|
||||
headless=True,
|
||||
max_requests_per_crawl=10,
|
||||
browser_type='firefox',
|
||||
storage_client=storage_client,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
"""Default request handler that processes each page during crawling."""
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
title = await context.page.query_selector('title')
|
||||
await context.push_data(
|
||||
{
|
||||
'url': context.request.loaded_url,
|
||||
'title': await title.inner_text() if title else None,
|
||||
}
|
||||
)
|
||||
|
||||
await context.enqueue_links()
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
data = await crawler.get_data()
|
||||
|
||||
# Return the results as JSON to the client
|
||||
return json.dumps(data.items)
|
||||
|
||||
|
||||
# Initialize the Litestar app with our route handler
|
||||
app = Litestar(route_handlers=[main])
|
||||
|
||||
# Start the Uvicorn server using the `PORT` environment variable provided by GCP
|
||||
# This is crucial - Cloud Run expects your app to listen on this specific port
|
||||
uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', '8080'))) # noqa: S104 # Use all interfaces in a container, safely
|
||||
@@ -0,0 +1,57 @@
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import timedelta
|
||||
|
||||
import functions_framework
|
||||
from flask import Request, Response
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
from crawlee.storage_clients import MemoryStorageClient
|
||||
|
||||
|
||||
async def main() -> str:
|
||||
# highlight-start
|
||||
# Disable writing storage data to the file system
|
||||
storage_client = MemoryStorageClient()
|
||||
# highlight-end
|
||||
|
||||
crawler = BeautifulSoupCrawler(
|
||||
storage_client=storage_client,
|
||||
max_request_retries=1,
|
||||
request_handler_timeout=timedelta(seconds=30),
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
'h1s': [h1.text for h1 in context.soup.find_all('h1')],
|
||||
'h2s': [h2.text for h2 in context.soup.find_all('h2')],
|
||||
'h3s': [h3.text for h3 in context.soup.find_all('h3')],
|
||||
}
|
||||
|
||||
await context.push_data(data)
|
||||
await context.enqueue_links()
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
# highlight-start
|
||||
# Extract data saved in `Dataset`
|
||||
data = await crawler.get_data()
|
||||
# Serialize to json string and return
|
||||
return json.dumps(data.items)
|
||||
# highlight-end
|
||||
|
||||
|
||||
@functions_framework.http
|
||||
def crawlee_run(request: Request) -> Response:
|
||||
# You can pass data to your crawler using `request`
|
||||
function_id = request.headers['Function-Execution-Id']
|
||||
response_str = asyncio.run(main())
|
||||
|
||||
# Return a response with the crawling results
|
||||
return Response(response=response_str, status=200)
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
id: gcp-cloud-run-functions
|
||||
title: Cloud Run functions
|
||||
description: Prepare your crawler to run in Cloud Run functions on Google Cloud Platform.
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
|
||||
import GoogleFunctions from '!!raw-loader!./code_examples/google/google_example.py';
|
||||
|
||||
[Google Cloud Run Functions](https://cloud.google.com/functions) is a serverless execution environment for running simple HTTP-based web scrapers. This service is best suited for lightweight crawlers that don't require browser rendering capabilities and can be executed via HTTP requests.
|
||||
|
||||
## Updating the project
|
||||
|
||||
For the project foundation, use <ApiLink to="class/BeautifulSoupCrawler">BeautifulSoupCrawler</ApiLink> as described in this [example](../examples/beautifulsoup-crawler).
|
||||
|
||||
Add [`functions-framework`](https://pypi.org/project/functions-framework/) to your dependencies file `requirements.txt`. If you're using a project manager like `poetry` or `uv`, export your dependencies to `requirements.txt`.
|
||||
|
||||
Update the project code to make it compatible with Cloud Functions and return data in JSON format. Also add an entry point that Cloud Functions will use to run the project.
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{GoogleFunctions.replace(/^.*?\n/, '')}
|
||||
</CodeBlock>
|
||||
|
||||
You can test your project locally. Start the server by running:
|
||||
|
||||
```bash
|
||||
functions-framework --target=crawlee_run
|
||||
```
|
||||
|
||||
Then make a GET request to `http://127.0.0.1:8080/`, for example in your browser.
|
||||
|
||||
## Deploying to Google Cloud Platform
|
||||
|
||||
In the Google Cloud dashboard, create a new function, allocate memory and CPUs to it, set region and function timeout.
|
||||
|
||||
When deploying, select **"Use an inline editor to create a function"**. This allows you to configure the project using only the Google Cloud Console dashboard.
|
||||
|
||||
Using the `inline editor`, update the function files according to your project. **Make sure** to update the `requirements.txt` file to match your project's dependencies.
|
||||
|
||||
Also, make sure to set the **Function entry point** to the name of the function decorated with `@functions_framework.http`, which in our case is `crawlee_run`.
|
||||
|
||||
After the Function deploys, you can test it by clicking the "Test" button. This button opens a popup with a `curl` script that calls your new Cloud Function. To avoid having to install the `gcloud` CLI application locally, you can also run this script in the Cloud Shell by clicking the link above the code block.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
id: gcp-cloud-run
|
||||
title: Cloud Run
|
||||
description: Prepare your crawler to run in Cloud Run on Google Cloud Platform.
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
|
||||
import GoogleCloudRun from '!!raw-loader!./code_examples/google/cloud_run_example.py';
|
||||
|
||||
|
||||
[Google Cloud Run](https://cloud.google.com/run) is a container-based serverless platform that allows you to run web crawlers with headless browsers. This service is recommended when your Crawlee applications need browser rendering capabilities, require more granular control, or have complex dependencies that aren't supported by [Cloud Functions](./gcp-cloud-run-functions).
|
||||
|
||||
GCP Cloud Run allows you to deploy using Docker containers, giving you full control over your environment and the flexibility to use any web server framework of your choice, unlike Cloud Functions which are limited to [Flask](https://flask.palletsprojects.com/en/stable/).
|
||||
|
||||
## Preparing the project
|
||||
|
||||
We'll prepare our project using [Litestar](https://litestar.dev/) and the [Uvicorn](https://www.uvicorn.org/) web server. The HTTP server handler will wrap the crawler to communicate with clients. Because the Cloud Run platform sees only an opaque Docker container, we have to take care of this bit ourselves.
|
||||
|
||||
:::info
|
||||
|
||||
GCP passes you an environment variable called `PORT` - your HTTP server is expected to be listening on this port (GCP exposes this one to the outer world).
|
||||
|
||||
:::
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{GoogleCloudRun.replace(/^.*?\n/, '')}
|
||||
</CodeBlock>
|
||||
|
||||
|
||||
:::tip
|
||||
|
||||
Always make sure to keep all the logic in the request handler - as with other FaaS services, your request handlers have to be **stateless.**
|
||||
|
||||
:::
|
||||
|
||||
## Deploying to Google Cloud Platform
|
||||
|
||||
Now, we’re ready to deploy! If you have initialized your project using `uvx crawlee create`, the initialization script has prepared a Dockerfile for you.
|
||||
|
||||
All you have to do now is run `gcloud run deploy` in your project folder (the one with your Dockerfile in it). The gcloud CLI application will ask you a few questions, such as what region you want to deploy your application in, or whether you want to make your application public or private.
|
||||
|
||||
After answering those questions, you should be able to see your application in the GCP dashboard and run it using the link you find there.
|
||||
|
||||
:::tip
|
||||
|
||||
In case your first execution of your newly created Cloud Run fails, try editing the Run configuration - mainly setting the available memory to 1GiB or more and updating the request timeout according to the size of the website you are scraping.
|
||||
|
||||
:::
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
id: add-data-to-dataset
|
||||
title: Add data to dataset
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/add_data_to_dataset_bs.py';
|
||||
import PlaywrightExample from '!!raw-loader!roa-loader!./code_examples/add_data_to_dataset_pw.py';
|
||||
import DatasetExample from '!!raw-loader!roa-loader!./code_examples/add_data_to_dataset_dataset.py';
|
||||
|
||||
This example demonstrates how to store extracted data into datasets using the <ApiLink to="class/PushDataFunction#open">`context.push_data`</ApiLink> helper function. If the specified dataset does not already exist, it will be created automatically. Additionally, you can save data to custom datasets by providing `dataset_id` or `dataset_name` parameters to the <ApiLink to="class/PushDataFunction#open">`push_data`</ApiLink> function.
|
||||
|
||||
<Tabs groupId="main">
|
||||
<TabItem value="BeautifulSoupCrawler" label="BeautifulSoupCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Each item in the dataset will be stored in its own file within the following directory:
|
||||
|
||||
```text
|
||||
{PROJECT_FOLDER}/storage/datasets/default/
|
||||
```
|
||||
|
||||
For more control, you can also open a dataset manually using the asynchronous constructor <ApiLink to="class/Dataset#open">`Dataset.open`</ApiLink>
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{DatasetExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
id: beautifulsoup-crawler
|
||||
title: BeautifulSoup crawler
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/beautifulsoup_crawler.py';
|
||||
|
||||
This example demonstrates how to use <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink> to crawl a list of URLs, load each URL using a plain HTTP request, parse the HTML using the [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) library and extract some data from it - the page title and all `<h1>`, `<h2>` and `<h3>` tags. This setup is perfect for scraping specific elements from web pages. Thanks to the well-known BeautifulSoup, you can easily navigate the HTML structure and retrieve the data you need with minimal code. It also shows how you can add optional pre-navigation hook to the crawler. Pre-navigation hooks are user defined functions that execute before sending the request.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
id: capture-screenshots-using-playwright
|
||||
title: Capture screenshots using Playwright
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import CaptureScreenshotExample from '!!raw-loader!roa-loader!./code_examples/capture_screenshot_using_playwright.py';
|
||||
|
||||
This example demonstrates how to capture screenshots of web pages using <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and store them in the key-value store.
|
||||
|
||||
The <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> is configured to automate the browsing and interaction with web pages. It uses headless Chromium as the browser type to perform these tasks. Each web page specified in the initial list of URLs is visited sequentially, and a screenshot of the page is captured using Playwright's `page.screenshot()` method.
|
||||
|
||||
The captured screenshots are stored in the key-value store, which is suitable for managing and storing files in various formats. In this case, screenshots are stored as PNG images with a unique key generated from the URL of the page.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{CaptureScreenshotExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
id: capturing-page-snapshots-with-error-snapshotter
|
||||
title: Capturing page snapshots with ErrorSnapshotter
|
||||
description: How to capture page snapshots on errors.
|
||||
---
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import ParselCrawlerWithErrorSnapshotter from '!!raw-loader!roa-loader!./code_examples/parsel_crawler_with_error_snapshotter.py';
|
||||
import PlaywrightCrawlerWithErrorSnapshotter from '!!raw-loader!roa-loader!./code_examples/playwright_crawler_with_error_snapshotter.py';
|
||||
|
||||
|
||||
This example demonstrates how to capture page snapshots on first occurrence of each unique error. The capturing happens automatically if you set `save_error_snapshots=True` in the crawler's <ApiLink to="class/Statistics">`Statistics`</ApiLink>. The error snapshot can contain `html` file and `jpeg` file that are created from the page where the unhandled exception was raised. Captured error snapshot files are saved to the default key-value store. Both <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and [HTTP crawlers](../guides/http-crawlers) are capable of capturing the html file, but only <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> is able to capture page screenshot as well.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="ParselCrawler" label="ParselCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{ ParselCrawlerWithErrorSnapshotter }
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{ PlaywrightCrawlerWithErrorSnapshotter }
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,66 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
from playwright.async_api import Route
|
||||
|
||||
from crawlee.crawlers import (
|
||||
AdaptivePlaywrightCrawler,
|
||||
AdaptivePlaywrightCrawlingContext,
|
||||
AdaptivePlaywrightPreNavCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Crawler created by following factory method will use `beautifulsoup`
|
||||
# for parsing static content.
|
||||
crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(
|
||||
max_requests_per_crawl=10, # Limit the max requests per crawl.
|
||||
playwright_crawler_specific_kwargs={'headless': False},
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler_for_label(
|
||||
context: AdaptivePlaywrightCrawlingContext,
|
||||
) -> None:
|
||||
# Do some processing using `parsed_content`
|
||||
context.log.info(context.parsed_content.title)
|
||||
|
||||
# Locate element h2 within 5 seconds
|
||||
h2 = await context.query_selector_one('h2', timedelta(milliseconds=5000))
|
||||
# Do stuff with element found by the selector
|
||||
context.log.info(h2)
|
||||
|
||||
# Find more links and enqueue them.
|
||||
await context.enqueue_links()
|
||||
# Save some data.
|
||||
await context.push_data({'Visited url': context.request.url})
|
||||
|
||||
@crawler.pre_navigation_hook
|
||||
async def hook(context: AdaptivePlaywrightPreNavCrawlingContext) -> None:
|
||||
"""Hook executed both in static sub crawler and playwright sub crawler.
|
||||
|
||||
Trying to access `context.page` in this hook would raise `AdaptiveContextError`
|
||||
for pages crawled without playwright."""
|
||||
context.log.info(f'pre navigation hook for: {context.request.url} ...')
|
||||
|
||||
@crawler.pre_navigation_hook(playwright_only=True)
|
||||
async def hook_playwright(context: AdaptivePlaywrightPreNavCrawlingContext) -> None:
|
||||
"""Hook executed only in playwright sub crawler.
|
||||
|
||||
It is safe to access `page` object.
|
||||
"""
|
||||
|
||||
async def some_routing_function(route: Route) -> None:
|
||||
await route.continue_()
|
||||
|
||||
await context.page.route('*/**', some_routing_function)
|
||||
context.log.info(
|
||||
f'Playwright only pre navigation hook for: {context.request.url} ...'
|
||||
)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://warehouse-theme-metal.myshopify.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler()
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
'html': str(context.soup)[:1000],
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(
|
||||
[
|
||||
'https://crawlee.dev',
|
||||
'https://apify.com',
|
||||
'https://example.com',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,15 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.storages import Dataset
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Open dataset manually using asynchronous constructor open().
|
||||
dataset = await Dataset.open()
|
||||
|
||||
# Interact with dataset directly.
|
||||
await dataset.push_data({'key': 'value'})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
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(),
|
||||
'html': str(await context.page.content())[:1000],
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(
|
||||
[
|
||||
'https://crawlee.dev',
|
||||
'https://apify.com',
|
||||
'https://example.com',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,57 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
from crawlee.crawlers import (
|
||||
BasicCrawlingContext,
|
||||
BeautifulSoupCrawler,
|
||||
BeautifulSoupCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create an instance of the BeautifulSoupCrawler class, a crawler that automatically
|
||||
# loads the URLs and parses their HTML using the BeautifulSoup library.
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# On error, retry each page at most once.
|
||||
max_request_retries=1,
|
||||
# Increase the timeout for processing each page to 30 seconds.
|
||||
request_handler_timeout=timedelta(seconds=30),
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
# The handler receives a context parameter, providing various properties and
|
||||
# helper methods. Here are a few key ones we use for demonstration:
|
||||
# - request: an instance of the Request class containing details such as the URL
|
||||
# being crawled and the HTTP method used.
|
||||
# - soup: the BeautifulSoup object containing the parsed HTML of the response.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
'h1s': [h1.text for h1 in context.soup.find_all('h1')],
|
||||
'h2s': [h2.text for h2 in context.soup.find_all('h2')],
|
||||
'h3s': [h3.text for h3 in context.soup.find_all('h3')],
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset. In local configuration,
|
||||
# the data will be stored as JSON files in ./storage/datasets/default.
|
||||
await context.push_data(data)
|
||||
|
||||
# Register pre navigation hook which will be called before each request.
|
||||
# This hook is optional and does not need to be defined at all.
|
||||
@crawler.pre_navigation_hook
|
||||
async def some_hook(context: BasicCrawlingContext) -> None:
|
||||
pass
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,56 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee._types import BasicCrawlingContext
|
||||
from crawlee.crawlers import BeautifulSoupCrawler
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Keep the crawler alive even when there are no requests to be processed now.
|
||||
keep_alive=True,
|
||||
)
|
||||
|
||||
def stop_crawler_if_url_visited(context: BasicCrawlingContext) -> None:
|
||||
"""Stop crawler once specific url is visited.
|
||||
|
||||
Example of guard condition to stop the crawler."""
|
||||
if context.request.url == 'https://crawlee.dev/docs/examples':
|
||||
crawler.stop(
|
||||
'Stop crawler that was in keep_alive state after specific url was visite'
|
||||
)
|
||||
else:
|
||||
context.log.info('keep_alive=True, waiting for more requests to come.')
|
||||
|
||||
async def add_request_later(url: str, after_s: int) -> None:
|
||||
"""Add requests to the queue after some time. Can be done by external code."""
|
||||
# Just an example of request being added to the crawler later,
|
||||
# when it is waiting due to `keep_alive=True`.
|
||||
await asyncio.sleep(after_s)
|
||||
await crawler.add_requests([url])
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BasicCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Stop crawler if some guard condition has been met.
|
||||
stop_crawler_if_url_visited(context)
|
||||
|
||||
# Start some tasks that will add some requests later to simulate real situation,
|
||||
# where requests are added later by external code.
|
||||
add_request_later_task1 = asyncio.create_task(
|
||||
add_request_later(url='https://crawlee.dev', after_s=1)
|
||||
)
|
||||
add_request_later_task2 = asyncio.create_task(
|
||||
add_request_later(url='https://crawlee.dev/docs/examples', after_s=5)
|
||||
)
|
||||
|
||||
# Run the crawler without the initial list of requests.
|
||||
# Wait for more requests to be added to the queue later due to `keep_alive=True`.
|
||||
await crawler.run()
|
||||
|
||||
await asyncio.gather(add_request_later_task1, add_request_later_task2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create an instance of the BeautifulSoupCrawler class, a crawler that automatically
|
||||
# loads the URLs and parses their HTML using the BeautifulSoup library.
|
||||
crawler = BeautifulSoupCrawler()
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
# The handler receives a context parameter, providing various properties and
|
||||
# helper methods. Here are a few key ones we use for demonstration:
|
||||
# - request: an instance of the Request class containing details such as the URL
|
||||
# being crawled and the HTTP method used.
|
||||
# - soup: the BeautifulSoup object containing the parsed HTML of the response.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Create custom condition to stop crawler once it finds what it is looking for.
|
||||
if 'crawlee' in context.request.url:
|
||||
crawler.stop(
|
||||
reason='Manual stop of crawler after finding `crawlee` in the url.'
|
||||
)
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset. In local configuration,
|
||||
# the data will be stored as JSON files in ./storage/datasets/default.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,47 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.storages import KeyValueStore
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
# Headless mode, set to False to see the browser in action.
|
||||
headless=False,
|
||||
# Browser types supported by Playwright.
|
||||
browser_type='chromium',
|
||||
)
|
||||
|
||||
# Open the default key-value store.
|
||||
kvs = await KeyValueStore.open()
|
||||
|
||||
# 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} ...')
|
||||
|
||||
# Capture the screenshot of the page using Playwright's API.
|
||||
screenshot = await context.page.screenshot()
|
||||
name = context.request.url.split('/')[-1]
|
||||
|
||||
# Store the screenshot in the key-value store.
|
||||
await kvs.set_value(
|
||||
key=f'screenshot-{name}',
|
||||
value=screenshot,
|
||||
content_type='image/png',
|
||||
)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(
|
||||
[
|
||||
'https://crawlee.dev',
|
||||
'https://apify.com',
|
||||
'https://example.com',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import logging
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from loguru import Record
|
||||
|
||||
|
||||
# Configure loguru interceptor to capture standard logging output
|
||||
class InterceptHandler(logging.Handler):
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
# Get corresponding Loguru level if it exists
|
||||
try:
|
||||
level: str | int = logger.level(record.levelname).name
|
||||
except ValueError:
|
||||
level = record.levelno
|
||||
|
||||
# Find caller from where originated the logged message
|
||||
frame, depth = inspect.currentframe(), 0
|
||||
while frame:
|
||||
filename = frame.f_code.co_filename
|
||||
is_logging = filename == logging.__file__
|
||||
is_frozen = 'importlib' in filename and '_bootstrap' in filename
|
||||
if depth > 0 and not (is_logging | is_frozen):
|
||||
break
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
dummy_record = logging.LogRecord('dummy', 0, 'dummy', 0, 'dummy', None, None)
|
||||
standard_attrs = set(dummy_record.__dict__.keys())
|
||||
extra_dict = {
|
||||
key: value
|
||||
for key, value in record.__dict__.items()
|
||||
if key not in standard_attrs
|
||||
}
|
||||
|
||||
(
|
||||
logger.bind(**extra_dict)
|
||||
.opt(depth=depth, exception=record.exc_info)
|
||||
.patch(lambda loguru_record: loguru_record.update({'name': record.name}))
|
||||
.log(level, record.getMessage())
|
||||
)
|
||||
|
||||
|
||||
# Configure loguru formatter
|
||||
def formatter(record: Record) -> str:
|
||||
basic_format = '[{name}] | <level>{level: ^8}</level> | - {message}'
|
||||
if record['extra']:
|
||||
basic_format = basic_format + ' {extra}'
|
||||
return f'{basic_format}\n'
|
||||
|
||||
|
||||
# Remove default loguru logger
|
||||
logger.remove()
|
||||
|
||||
# Set up loguru with JSONL serialization in file `crawler.log`
|
||||
logger.add('crawler.log', format=formatter, serialize=True, level='INFO')
|
||||
|
||||
# Set up loguru logger for console
|
||||
logger.add(sys.stderr, format=formatter, colorize=True, level='INFO')
|
||||
|
||||
# Configure standard logging to use our interceptor
|
||||
logging.basicConfig(handlers=[InterceptHandler()], level=logging.INFO, force=True)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Initialize crawler with disabled table logs
|
||||
crawler = HttpCrawler(
|
||||
configure_logging=False, # Disable default logging configuration
|
||||
statistics_log_format='inline', # Set inline formatting for statistics logs
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Run the crawler
|
||||
await crawler.run(['https://www.crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all links found on the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# 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} ...')
|
||||
|
||||
# Enqueue all links found on the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler()
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(
|
||||
[
|
||||
'https://crawlee.dev',
|
||||
'https://apify.com',
|
||||
'https://example.com',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
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} ...')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(
|
||||
[
|
||||
'https://crawlee.dev',
|
||||
'https://apify.com',
|
||||
'https://example.com',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,29 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Glob
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all the documentation links found on the page, except for the examples.
|
||||
await context.enqueue_links(
|
||||
include=[Glob('https://crawlee.dev/docs/**')],
|
||||
exclude=[Glob('https://crawlee.dev/docs/examples')],
|
||||
)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,29 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Glob
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# 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} ...')
|
||||
|
||||
# Enqueue all the documentation links found on the page, except for the examples.
|
||||
await context.enqueue_links(
|
||||
include=[Glob('https://crawlee.dev/docs/**')],
|
||||
exclude=[Glob('https://crawlee.dev/docs/examples')],
|
||||
)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all links found on the page. Any URLs found will be matched by
|
||||
# this strategy, even if they go off the site you are currently crawling.
|
||||
await context.enqueue_links(strategy='all')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Setting the strategy to same domain will enqueue all links found that
|
||||
# are on the same hostname as request.loaded_url or request.url.
|
||||
await context.enqueue_links(strategy='same-domain')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Setting the strategy to same hostname will enqueue all links found that are on
|
||||
# the same hostname (including subdomains) as request.loaded_url or request.url.
|
||||
await context.enqueue_links(strategy='same-hostname')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Setting the strategy to same origin will enqueue all links found that are on
|
||||
# the same origin as request.loaded_url or request.url.
|
||||
await context.enqueue_links(strategy='same-origin')
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
import asyncio
|
||||
import csv
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
}
|
||||
|
||||
# Enqueue all links found on the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
# Export the entire dataset to a CSV file.
|
||||
# Use semicolon as delimiter and always quote strings.
|
||||
await crawler.export_data(path='results.csv', delimiter=';', quoting=csv.QUOTE_ALL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,38 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
}
|
||||
|
||||
# Enqueue all links found on the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
# Export the entire dataset to a JSON file.
|
||||
# Set ensure_ascii=False to allow Unicode characters in the output.
|
||||
await crawler.export_data(path='results.json', ensure_ascii=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,36 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Glob
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract all the documentation links found on the page, except for the examples.
|
||||
extracted_links = await context.extract_links(
|
||||
include=[Glob('https://crawlee.dev/docs/**')],
|
||||
exclude=[Glob('https://crawlee.dev/docs/examples')],
|
||||
)
|
||||
# Some very custom filtering which can't be achieved by `extract_links` arguments.
|
||||
max_link_length = 30
|
||||
filtered_links = [
|
||||
link for link in extracted_links if len(link.url) < max_link_length
|
||||
]
|
||||
# Add filtered links to the request queue.
|
||||
await context.add_requests(filtered_links)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,36 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Glob
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# 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 all the documentation links found on the page, except for the examples.
|
||||
extracted_links = await context.extract_links(
|
||||
include=[Glob('https://crawlee.dev/docs/**')],
|
||||
exclude=[Glob('https://crawlee.dev/docs/examples')],
|
||||
)
|
||||
# Some very custom filtering which can't be achieved by `extract_links` arguments.
|
||||
max_link_length = 30
|
||||
filtered_links = [
|
||||
link for link in extracted_links if len(link.url) < max_link_length
|
||||
]
|
||||
# Add filtered links to the request queue.
|
||||
await context.add_requests(filtered_links)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler()
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
response = (await context.http_response.read()).decode('utf-8')
|
||||
context.log.info(f'Response: {response}') # To see the response in the logs.
|
||||
|
||||
# Prepare a POST request to the form endpoint.
|
||||
request = Request.from_url(
|
||||
url='https://httpbin.org/post',
|
||||
method='POST',
|
||||
headers={'content-type': 'application/x-www-form-urlencoded'},
|
||||
payload=urlencode(
|
||||
{
|
||||
'custname': 'John Doe',
|
||||
'custtel': '1234567890',
|
||||
'custemail': 'johndoe@example.com',
|
||||
'size': 'large',
|
||||
'topping': ['bacon', 'cheese', 'mushroom'],
|
||||
'delivery': '13:00',
|
||||
'comments': 'Please ring the doorbell upon arrival.',
|
||||
}
|
||||
).encode(),
|
||||
)
|
||||
|
||||
# Run the crawler with the initial list of requests.
|
||||
await crawler.run([request])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,28 @@
|
||||
import asyncio
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from crawlee import Request
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Prepare a POST request to the form endpoint.
|
||||
request = Request.from_url(
|
||||
url='https://httpbin.org/post',
|
||||
method='POST',
|
||||
headers={'content-type': 'application/x-www-form-urlencoded'},
|
||||
payload=urlencode(
|
||||
{
|
||||
'custname': 'John Doe',
|
||||
'custtel': '1234567890',
|
||||
'custemail': 'johndoe@example.com',
|
||||
'size': 'large',
|
||||
'topping': ['bacon', 'cheese', 'mushroom'],
|
||||
'delivery': '13:00',
|
||||
'comments': 'Please ring the doorbell upon arrival.',
|
||||
}
|
||||
).encode(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,47 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BasicCrawlingContext, ParselCrawler, ParselCrawlingContext
|
||||
|
||||
# Regex for identifying email addresses on a webpage.
|
||||
EMAIL_REGEX = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = ParselCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.selector.xpath('//title/text()').get(),
|
||||
'email_address_list': context.selector.re(EMAIL_REGEX),
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Enqueue all links found on the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Register pre navigation hook which will be called before each request.
|
||||
# This hook is optional and does not need to be defined at all.
|
||||
@crawler.pre_navigation_hook
|
||||
async def some_hook(context: BasicCrawlingContext) -> None:
|
||||
pass
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://github.com'])
|
||||
|
||||
# Export the entire dataset to a JSON file.
|
||||
await crawler.export_data(path='results.json')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,31 @@
|
||||
import asyncio
|
||||
from random import choice
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
from crawlee.statistics import Statistics
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = ParselCrawler(
|
||||
statistics=Statistics.with_default_state(save_error_snapshots=True)
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
# Simulate various errors to demonstrate `ErrorSnapshotter`
|
||||
# saving only the first occurrence of unique error.
|
||||
await context.enqueue_links()
|
||||
random_number = choice(range(10))
|
||||
if random_number == 1:
|
||||
raise KeyError('Some KeyError')
|
||||
if random_number == 2:
|
||||
raise ValueError('Some ValueError')
|
||||
if random_number == 3:
|
||||
raise RuntimeError('Some RuntimeError')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,36 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import (
|
||||
PlaywrightCrawler,
|
||||
PlaywrightCrawlingContext,
|
||||
PlaywrightPreNavCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# 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} ...')
|
||||
|
||||
await context.enqueue_links()
|
||||
|
||||
# Define the hook, which will be called before every request.
|
||||
@crawler.pre_navigation_hook
|
||||
async def navigation_hook(context: PlaywrightPreNavCrawlingContext) -> None:
|
||||
context.log.info(f'Navigating to {context.request.url} ...')
|
||||
|
||||
# Block all requests to URLs that include `adsbygoogle.js` and also all defaults.
|
||||
await context.block_requests(extra_url_patterns=['adsbygoogle.js'])
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,67 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import (
|
||||
PlaywrightCrawler,
|
||||
PlaywrightCrawlingContext,
|
||||
PlaywrightPreNavCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
# Headless mode, set to False to see the browser in action.
|
||||
headless=False,
|
||||
# Browser types supported by Playwright.
|
||||
browser_type='chromium',
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
# The handler receives a context parameter, providing various properties and
|
||||
# helper methods. Here are a few key ones we use for demonstration:
|
||||
# - request: an instance of the Request class containing details such as the URL
|
||||
# being crawled and the HTTP method used.
|
||||
# - page: Playwright's Page object, which allows interaction with the web page
|
||||
# (see https://playwright.dev/python/docs/api/class-page for more details).
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Extract data from the page using Playwright's API.
|
||||
posts = await context.page.query_selector_all('.athing')
|
||||
data = []
|
||||
|
||||
for post in posts:
|
||||
# Get the HTML elements for the title and rank within each post.
|
||||
title_element = await post.query_selector('.title a')
|
||||
rank_element = await post.query_selector('.rank')
|
||||
|
||||
# Extract the data we want from the elements.
|
||||
title = await title_element.inner_text() if title_element else None
|
||||
rank = await rank_element.inner_text() if rank_element else None
|
||||
href = await title_element.get_attribute('href') if title_element else None
|
||||
|
||||
data.append({'title': title, 'rank': rank, 'href': href})
|
||||
|
||||
# Push the extracted data to the default dataset. In local configuration,
|
||||
# the data will be stored as JSON files in ./storage/datasets/default.
|
||||
await context.push_data(data)
|
||||
|
||||
# Find a link to the next page and enqueue it if it exists.
|
||||
await context.enqueue_links(selector='.morelink')
|
||||
|
||||
# Define a hook that will be called each time before navigating to a new URL.
|
||||
# The hook receives a context parameter, providing access to the request and
|
||||
# browser page among other things. In this example, we log the URL being
|
||||
# navigated to.
|
||||
@crawler.pre_navigation_hook
|
||||
async def log_navigation_url(context: PlaywrightPreNavCrawlingContext) -> None:
|
||||
context.log.info(f'Navigating to {context.request.url} ...')
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://news.ycombinator.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,69 @@
|
||||
import asyncio
|
||||
|
||||
# Camoufox is external package and needs to be installed. It is not included in crawlee.
|
||||
from camoufox import AsyncNewBrowser
|
||||
from typing_extensions import override
|
||||
|
||||
from crawlee.browsers import (
|
||||
BrowserPool,
|
||||
PlaywrightBrowserController,
|
||||
PlaywrightBrowserPlugin,
|
||||
)
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
class CamoufoxPlugin(PlaywrightBrowserPlugin):
|
||||
"""Example browser plugin that uses Camoufox browser,
|
||||
but otherwise keeps the functionality of PlaywrightBrowserPlugin.
|
||||
"""
|
||||
|
||||
@override
|
||||
async def new_browser(self) -> PlaywrightBrowserController:
|
||||
if not self._playwright:
|
||||
raise RuntimeError('Playwright browser plugin is not initialized.')
|
||||
|
||||
return PlaywrightBrowserController(
|
||||
browser=await AsyncNewBrowser(
|
||||
self._playwright, **self._browser_launch_options
|
||||
),
|
||||
# Increase, if camoufox can handle it in your use case.
|
||||
max_open_pages_per_browser=1,
|
||||
# This turns off the crawlee header_generation. Camoufox has its own.
|
||||
header_generator=None,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
# Custom browser pool. Gives users full control over browsers used by the crawler.
|
||||
browser_pool=BrowserPool(plugins=[CamoufoxPlugin()]),
|
||||
)
|
||||
|
||||
# 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 some data from the page using Playwright's API.
|
||||
posts = await context.page.query_selector_all('.athing')
|
||||
for post in posts:
|
||||
# Get the HTML elements for the title and rank within each post.
|
||||
title_element = await post.query_selector('.title a')
|
||||
|
||||
# Extract the data we want from the elements.
|
||||
title = await title_element.inner_text() if title_element else None
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data({'title': title})
|
||||
|
||||
# Find a link to the next page and enqueue it if it exists.
|
||||
await context.enqueue_links(selector='.morelink')
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://news.ycombinator.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,31 @@
|
||||
import asyncio
|
||||
from random import choice
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.statistics import Statistics
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
statistics=Statistics.with_default_state(save_error_snapshots=True)
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
# Simulate various errors to demonstrate `ErrorSnapshotter`
|
||||
# saving only the first occurrence of unique error.
|
||||
await context.enqueue_links()
|
||||
random_number = choice(range(10))
|
||||
if random_number == 1:
|
||||
raise KeyError('Some KeyError')
|
||||
if random_number == 2:
|
||||
raise ValueError('Some ValueError')
|
||||
if random_number == 3:
|
||||
raise RuntimeError('Some RuntimeError')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.fingerprint_suite import (
|
||||
DefaultFingerprintGenerator,
|
||||
HeaderGeneratorOptions,
|
||||
ScreenOptions,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Use default fingerprint generator with desired fingerprint options.
|
||||
# Generator will generate real looking browser fingerprint based on the options.
|
||||
# Unspecified fingerprint options will be automatically selected by the generator.
|
||||
fingerprint_generator = DefaultFingerprintGenerator(
|
||||
header_options=HeaderGeneratorOptions(browsers=['chrome']),
|
||||
screen_options=ScreenOptions(min_width=400),
|
||||
)
|
||||
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
# Headless mode, set to False to see the browser in action.
|
||||
headless=False,
|
||||
# Browser types supported by Playwright.
|
||||
browser_type='chromium',
|
||||
# Fingerprint generator to be used. By default no fingerprint generation is done.
|
||||
fingerprint_generator=fingerprint_generator,
|
||||
)
|
||||
|
||||
# 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} ...')
|
||||
|
||||
# Find a link to the next page and enqueue it if it exists.
|
||||
await context.enqueue_links(selector='.morelink')
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://news.ycombinator.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,36 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import SkippedReason
|
||||
from crawlee.crawlers import (
|
||||
BeautifulSoupCrawler,
|
||||
BeautifulSoupCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Initialize the crawler with robots.txt compliance enabled
|
||||
crawler = BeautifulSoupCrawler(respect_robots_txt_file=True)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# highlight-start
|
||||
# This handler is called when a request is skipped
|
||||
@crawler.on_skipped_request
|
||||
async def skipped_request_handler(url: str, reason: SkippedReason) -> None:
|
||||
# Check if the request was skipped due to robots.txt rules
|
||||
if reason == 'robots_txt':
|
||||
crawler.log.info(f'Skipped {url} due to robots.txt rules.')
|
||||
|
||||
# highlight-end
|
||||
|
||||
# Start the crawler with the specified URLs
|
||||
# The login URL will be skipped and handled by the skipped_request_handler
|
||||
await crawler.run(
|
||||
['https://news.ycombinator.com/', 'https://news.ycombinator.com/login']
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import (
|
||||
BeautifulSoupCrawler,
|
||||
BeautifulSoupCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Initialize the crawler with robots.txt compliance enabled
|
||||
crawler = BeautifulSoupCrawler(respect_robots_txt_file=True)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Start the crawler with the specified URLs
|
||||
# The crawler will check the robots.txt file before making requests
|
||||
# In this example, 'https://news.ycombinator.com/login' will be skipped
|
||||
# because it's disallowed in the site's robots.txt file
|
||||
await crawler.run(
|
||||
['https://news.ycombinator.com/', 'https://news.ycombinator.com/login']
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,40 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import ConcurrencySettings, service_locator
|
||||
from crawlee.crawlers import (
|
||||
BeautifulSoupCrawler,
|
||||
BeautifulSoupCrawlingContext,
|
||||
)
|
||||
|
||||
# Disable clearing the `RequestQueue`, `KeyValueStore` and `Dataset` on each run.
|
||||
# This makes the scraper continue from where it left off in the previous run.
|
||||
# The recommended way to achieve this behavior is setting the environment variable
|
||||
# `CRAWLEE_PURGE_ON_START=0`
|
||||
configuration = service_locator.get_configuration()
|
||||
configuration.purge_on_start = False
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Let's slow down the crawler for a demonstration
|
||||
concurrency_settings=ConcurrencySettings(max_tasks_per_minute=20)
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# List of links for crawl
|
||||
requests = [
|
||||
'https://crawlee.dev',
|
||||
'https://crawlee.dev/python/docs',
|
||||
'https://crawlee.dev/python/docs/examples',
|
||||
'https://crawlee.dev/python/docs/guides',
|
||||
'https://crawlee.dev/python/docs/quick-start',
|
||||
]
|
||||
|
||||
await crawler.run(requests)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,94 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import ConcurrencySettings
|
||||
from crawlee.crawlers import (
|
||||
ParselCrawler,
|
||||
ParselCrawlingContext,
|
||||
PlaywrightCrawler,
|
||||
PlaywrightCrawlingContext,
|
||||
)
|
||||
from crawlee.sessions import SessionPool
|
||||
from crawlee.storages import RequestQueue
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Open request queues for both crawlers with different aliases
|
||||
playwright_rq = await RequestQueue.open(alias='playwright-requests')
|
||||
parsel_rq = await RequestQueue.open(alias='parsel-requests')
|
||||
|
||||
# Use a shared session pool between both crawlers
|
||||
async with SessionPool() as session_pool:
|
||||
playwright_crawler = PlaywrightCrawler(
|
||||
# Set the request queue for Playwright crawler
|
||||
request_manager=playwright_rq,
|
||||
session_pool=session_pool,
|
||||
# Configure concurrency settings for Playwright crawler
|
||||
concurrency_settings=ConcurrencySettings(
|
||||
max_concurrency=5, desired_concurrency=5
|
||||
),
|
||||
# Set `keep_alive`` so that the crawler does not stop working when there are
|
||||
# no requests in the queue.
|
||||
keep_alive=True,
|
||||
)
|
||||
|
||||
parsel_crawler = ParselCrawler(
|
||||
# Set the request queue for Parsel crawler
|
||||
request_manager=parsel_rq,
|
||||
session_pool=session_pool,
|
||||
# Configure concurrency settings for Parsel crawler
|
||||
concurrency_settings=ConcurrencySettings(
|
||||
max_concurrency=10, desired_concurrency=10
|
||||
),
|
||||
# Set maximum requests per crawl for Parsel crawler
|
||||
max_requests_per_crawl=50,
|
||||
)
|
||||
|
||||
@playwright_crawler.router.default_handler
|
||||
async def handle_playwright(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Playwright Processing {context.request.url}...')
|
||||
|
||||
title = await context.page.title()
|
||||
# Push the extracted data to the dataset for Playwright crawler
|
||||
await context.push_data(
|
||||
{'title': title, 'url': context.request.url, 'source': 'playwright'},
|
||||
dataset_name='playwright-data',
|
||||
)
|
||||
|
||||
@parsel_crawler.router.default_handler
|
||||
async def handle_parsel(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Parsel Processing {context.request.url}...')
|
||||
|
||||
title = context.parsed_content.css('title::text').get()
|
||||
# Push the extracted data to the dataset for Parsel crawler
|
||||
await context.push_data(
|
||||
{'title': title, 'url': context.request.url, 'source': 'parsel'},
|
||||
dataset_name='parsel-data',
|
||||
)
|
||||
|
||||
# Enqueue links to the Playwright request queue for blog pages
|
||||
await context.enqueue_links(
|
||||
selector='a[href*="/blog/"]', rq_alias='playwright-requests'
|
||||
)
|
||||
# Enqueue other links to the Parsel request queue
|
||||
await context.enqueue_links(selector='a:not([href*="/blog/"])')
|
||||
|
||||
# Start the Playwright crawler in the background
|
||||
background_crawler_task = asyncio.create_task(playwright_crawler.run([]))
|
||||
|
||||
# Run the Parsel crawler with the initial URL and wait for it to finish
|
||||
await parsel_crawler.run(['https://crawlee.dev/blog'])
|
||||
|
||||
# Wait for the Playwright crawler to finish processing all requests
|
||||
while not await playwright_rq.is_empty():
|
||||
playwright_crawler.log.info('Waiting for Playwright crawler to finish...')
|
||||
await asyncio.sleep(5)
|
||||
|
||||
# Stop the Playwright crawler after all requests are processed
|
||||
playwright_crawler.stop()
|
||||
|
||||
# Wait for the background Playwright crawler task to complete
|
||||
await background_crawler_task
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,54 @@
|
||||
import asyncio
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
# Profile name to use (usually 'Default' for single profile setups)
|
||||
PROFILE_NAME = 'Default'
|
||||
|
||||
# Paths to Chrome profiles in your system (example for Windows)
|
||||
# Use `chrome://version/` to find your profile path
|
||||
PROFILE_PATH = Path(Path.home(), 'AppData', 'Local', 'Google', 'Chrome', 'User Data')
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create a temporary folder to copy the profile to
|
||||
with TemporaryDirectory(prefix='crawlee-') as tmpdirname:
|
||||
tmp_profile_dir = Path(tmpdirname)
|
||||
|
||||
# Copy the profile to a temporary folder
|
||||
shutil.copytree(
|
||||
PROFILE_PATH / PROFILE_NAME,
|
||||
tmp_profile_dir / PROFILE_NAME,
|
||||
dirs_exist_ok=True,
|
||||
)
|
||||
|
||||
crawler = PlaywrightCrawler(
|
||||
headless=False,
|
||||
# Use the installed Chrome browser
|
||||
browser_type='chrome',
|
||||
# Disable fingerprints to preserve profile identity
|
||||
fingerprint_generator=None,
|
||||
# Set user data directory to temp folder
|
||||
user_data_dir=tmp_profile_dir,
|
||||
browser_launch_options={
|
||||
# Slow down actions to mimic human behavior
|
||||
'slow_mo': 200,
|
||||
'args': [
|
||||
# Use the specified profile
|
||||
f'--profile-directory={PROFILE_NAME}',
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Visiting {context.request.url}')
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
# Replace this with your actual Firefox profile name
|
||||
# Find it at about:profiles in Firefox
|
||||
PROFILE_NAME = 'your-profile-name-here'
|
||||
|
||||
# Paths to Firefox profiles in your system (example for Windows)
|
||||
# Use `about:profiles` to find your profile path
|
||||
PROFILE_PATH = Path(
|
||||
Path.home(), 'AppData', 'Roaming', 'Mozilla', 'Firefox', 'Profiles', PROFILE_NAME
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Use Firefox browser type
|
||||
browser_type='firefox',
|
||||
# Disable fingerprints to use the profile as is
|
||||
fingerprint_generator=None,
|
||||
headless=False,
|
||||
# Path to your Firefox profile
|
||||
user_data_dir=PROFILE_PATH,
|
||||
browser_launch_options={
|
||||
'args': [
|
||||
# Required to avoid version conflicts
|
||||
'--allow-downgrade'
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Visiting {context.request.url}')
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,101 @@
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
|
||||
from yarl import URL
|
||||
|
||||
from crawlee import RequestOptions, RequestTransformAction
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
from crawlee.http_clients import ImpitHttpClient
|
||||
from crawlee.request_loaders import SitemapRequestLoader
|
||||
|
||||
|
||||
# Create a transform_request_function that maps request options based on the host in
|
||||
# the URL
|
||||
def create_transform_request(
|
||||
data_mapper: dict[str, dict],
|
||||
) -> Callable[[RequestOptions], RequestOptions | RequestTransformAction]:
|
||||
def transform_request(
|
||||
request_options: RequestOptions,
|
||||
) -> RequestOptions | RequestTransformAction:
|
||||
# According to the Sitemap protocol, all URLs in a Sitemap must be from a single
|
||||
# host.
|
||||
request_host = URL(request_options['url']).host
|
||||
|
||||
if request_host and (mapping_data := data_mapper.get(request_host)):
|
||||
# Set properties from the mapping data
|
||||
if 'label' in mapping_data:
|
||||
request_options['label'] = mapping_data['label']
|
||||
if 'user_data' in mapping_data:
|
||||
request_options['user_data'] = mapping_data['user_data']
|
||||
|
||||
return request_options
|
||||
|
||||
return 'unchanged'
|
||||
|
||||
return transform_request
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Prepare data mapping for hosts
|
||||
apify_host = URL('https://apify.com/sitemap.xml').host
|
||||
crawlee_host = URL('https://crawlee.dev/sitemap.xml').host
|
||||
|
||||
if not apify_host or not crawlee_host:
|
||||
raise ValueError('Unable to extract host from URLs')
|
||||
|
||||
data_map = {
|
||||
apify_host: {
|
||||
'label': 'apify',
|
||||
'user_data': {'source': 'apify'},
|
||||
},
|
||||
crawlee_host: {
|
||||
'label': 'crawlee',
|
||||
'user_data': {'source': 'crawlee'},
|
||||
},
|
||||
}
|
||||
|
||||
# Initialize the SitemapRequestLoader with the transform function
|
||||
async with SitemapRequestLoader(
|
||||
# Set the sitemap URLs and the HTTP client
|
||||
sitemap_urls=['https://crawlee.dev/sitemap.xml', 'https://apify.com/sitemap.xml'],
|
||||
http_client=ImpitHttpClient(),
|
||||
transform_request_function=create_transform_request(data_map),
|
||||
) as sitemap_loader:
|
||||
# Convert the sitemap loader to a request manager
|
||||
request_manager = await sitemap_loader.to_tandem()
|
||||
|
||||
# Create and configure the crawler
|
||||
crawler = BeautifulSoupCrawler(
|
||||
request_manager=request_manager,
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Create default handler for requests without a specific label
|
||||
@crawler.router.default_handler
|
||||
async def handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
source = context.request.user_data.get('source', 'unknown')
|
||||
context.log.info(
|
||||
f'Processing request: {context.request.url} from source: {source}'
|
||||
)
|
||||
|
||||
# Create handler for requests labeled 'apify'
|
||||
@crawler.router.handler('apify')
|
||||
async def apify_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
source = context.request.user_data.get('source', 'unknown')
|
||||
context.log.info(
|
||||
f'Apify handler processing: {context.request.url} from source: {source}'
|
||||
)
|
||||
|
||||
# Create handler for requests labeled 'crawlee'
|
||||
@crawler.router.handler('crawlee')
|
||||
async def crawlee_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
source = context.request.user_data.get('source', 'unknown')
|
||||
context.log.info(
|
||||
f'Crawlee handler processing: {context.request.url} from source: {source}'
|
||||
)
|
||||
|
||||
await crawler.run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: crawl-all-links-on-website
|
||||
title: Crawl all links on website
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/crawl_all_links_on_website_bs.py';
|
||||
import PlaywrightExample from '!!raw-loader!roa-loader!./code_examples/crawl_all_links_on_website_pw.py';
|
||||
|
||||
This example uses the <ApiLink to="class/EnqueueLinksFunction">`enqueue_links`</ApiLink> helper to add new links to the <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> as the crawler navigates from page to page. By automatically discovering and enqueuing all links on a given page, the crawler can systematically scrape an entire website. This approach is ideal for web scraping tasks where you need to collect data from multiple interconnected pages.
|
||||
|
||||
:::tip
|
||||
|
||||
If no options are given, by default the method will only add links that are under the same subdomain. This behavior can be controlled with the `strategy` option, which is an instance of the `EnqueueStrategy` type alias. You can find more info about this option in the [Crawl website with relative links](./crawl-website-with-relative-links) example.
|
||||
|
||||
:::
|
||||
|
||||
<Tabs groupId="main">
|
||||
<TabItem value="BeautifulSoupCrawler" label="BeautifulSoupCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
id: crawl-multiple-urls
|
||||
title: Crawl multiple URLs
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/crawl_multiple_urls_bs.py';
|
||||
import PlaywrightExample from '!!raw-loader!roa-loader!./code_examples/crawl_multiple_urls_pw.py';
|
||||
|
||||
This example demonstrates how to crawl a specified list of URLs using different crawlers. You'll learn how to set up the crawler, define a request handler, and run the crawler with multiple URLs. This setup is useful for scraping data from multiple pages or websites concurrently.
|
||||
|
||||
<Tabs groupId="main">
|
||||
<TabItem value="BeautifulSoupCrawler" label="BeautifulSoupCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
id: crawl-specific-links-on-website
|
||||
title: Crawl specific links on website
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/crawl_specific_links_on_website_bs.py';
|
||||
import PlaywrightExample from '!!raw-loader!roa-loader!./code_examples/crawl_specific_links_on_website_pw.py';
|
||||
|
||||
import BeautifulSoupExampleExtractAndAdd from '!!raw-loader!roa-loader!./code_examples/extract_and_add_specific_links_on_website_bs.py';
|
||||
import PlaywrightExampleExtractAndAdd from '!!raw-loader!roa-loader!./code_examples/extract_and_add_specific_links_on_website_pw.py';
|
||||
|
||||
This example demonstrates how to crawl a website while targeting specific patterns of links. By utilizing the <ApiLink to="class/EnqueueLinksFunction">`enqueue_links`</ApiLink> helper, you can pass `include` or `exclude` parameters to improve your crawling strategy. This approach ensures that only the links matching the specified patterns are added to the <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink>. Both `include` and `exclude` support lists of globs or regular expressions. This functionality is great for focusing on relevant sections of a website and avoiding scraping unnecessary or irrelevant content.
|
||||
|
||||
<Tabs groupId="first-example">
|
||||
<TabItem value="BeautifulSoupCrawler" label="BeautifulSoupCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Even more control over the enqueued links
|
||||
|
||||
<ApiLink to="class/EnqueueLinksFunction">`enqueue_links`</ApiLink> is a convenience helper and internally it calls <ApiLink to="class/ExtractLinksFunction">`extract_links`</ApiLink> to find the links and <ApiLink to="class/AddRequestsFunction">`add_requests`</ApiLink> to add them to the queue. If you need some additional custom filtering of the extracted links before enqueuing them, then consider using <ApiLink to="class/ExtractLinksFunction">`extract_links`</ApiLink> and <ApiLink to="class/AddRequestsFunction">`add_requests`</ApiLink> instead of the <ApiLink to="class/EnqueueLinksFunction">`enqueue_links`</ApiLink>
|
||||
|
||||
<Tabs groupId="second-example">
|
||||
<TabItem value="BeautifulSoupCrawler" label="BeautifulSoupCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExampleExtractAndAdd}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="PlaywrightCrawler" label="PlaywrightCrawler">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightExampleExtractAndAdd}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
id: crawl-website-with-relative-links
|
||||
title: Crawl website with relative links
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import AllLinksExample from '!!raw-loader!roa-loader!./code_examples/crawl_website_with_relative_links_all_links.py';
|
||||
import SameDomainExample from '!!raw-loader!roa-loader!./code_examples/crawl_website_with_relative_links_same_domain.py';
|
||||
import SameHostnameExample from '!!raw-loader!roa-loader!./code_examples/crawl_website_with_relative_links_same_hostname.py';
|
||||
import SameOriginExample from '!!raw-loader!roa-loader!./code_examples/crawl_website_with_relative_links_same_origin.py';
|
||||
|
||||
When crawling a website, you may encounter various types of links that you wish to include in your crawl. To facilitate this, we provide the <ApiLink to="class/EnqueueLinksFunction">`enqueue_links`</ApiLink> method on the crawler context, which will automatically find and add these links to the crawler's <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink>. This method simplifies the process of handling different types of links, including relative links, by automatically resolving them based on the page's context.
|
||||
|
||||
:::note
|
||||
|
||||
For these examples, we are using the <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>. However, the same method is available for other crawlers as well. You can use it in exactly the same way.
|
||||
|
||||
:::
|
||||
|
||||
`EnqueueStrategy` type alias provides four distinct strategies for crawling relative links:
|
||||
|
||||
- `all` - Enqueues all links found, regardless of the domain they point to. This strategy is useful when you want to follow every link, including those that navigate to external websites.
|
||||
- `same-domain` - Enqueues all links found that share the same domain name, including any possible subdomains. This strategy ensures that all links within the same top-level and base domain are included.
|
||||
- `same-hostname` - Enqueues all links found for the exact same hostname. This is the **default** strategy, and it restricts the crawl to links that have the same hostname as the current page, excluding subdomains.
|
||||
- `same-origin` - Enqueues all links found that share the same origin. The same origin refers to URLs that share the same protocol, domain, and port, ensuring a strict scope for the crawl.
|
||||
|
||||
<Tabs groupId="main">
|
||||
<TabItem value="all_links" label="All links">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{AllLinksExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="same-domain" label="Same domain">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{SameDomainExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="same-hostname" label="Same hostname">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{SameHostnameExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="same-origin" label="Same origin">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{SameOriginExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
id: crawler-keep-alive
|
||||
title: Keep a Crawler alive waiting for more requests
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/beautifulsoup_crawler_keep_alive.py';
|
||||
|
||||
This example demonstrates how to keep crawler alive even when there are no requests at the moment by using `keep_alive=True` argument of <ApiLink to="class/BasicCrawler#__init__">`BasicCrawler.__init__`</ApiLink>. This is available to all crawlers that inherit from <ApiLink to="class/BasicCrawler">`BasicCrawler`</ApiLink> and in the example below it is shown on <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>. To stop the crawler that was started with `keep_alive=True` you can call `crawler.stop()`.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
id: crawler-stop
|
||||
title: Stopping a Crawler with stop method
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import BeautifulSoupExample from '!!raw-loader!roa-loader!./code_examples/beautifulsoup_crawler_stop.py';
|
||||
|
||||
This example demonstrates how to use `stop` method of <ApiLink to="class/BasicCrawler">`BasicCrawler`</ApiLink> to stop crawler once the crawler finds what it is looking for. This method is available to all crawlers that inherit from <ApiLink to="class/BasicCrawler">`BasicCrawler`</ApiLink> and in the example below it is shown on <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>. Simply call `crawler.stop()` to stop the crawler. It will not continue to crawl through new requests. Requests that are already being concurrently processed are going to get finished. It is possible to call `stop` method with optional argument `reason` that is a string that will be used in logs and it can improve logs readability especially if you have multiple different conditions for triggering `stop`.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{BeautifulSoupExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: export-entire-dataset-to-file
|
||||
title: Export entire dataset to file
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import JsonExample from '!!raw-loader!roa-loader!./code_examples/export_entire_dataset_to_file_json.py';
|
||||
import CsvExample from '!!raw-loader!roa-loader!./code_examples/export_entire_dataset_to_file_csv.py';
|
||||
|
||||
This example demonstrates how to use the <ApiLink to="class/BasicCrawler#export_data">`BasicCrawler.export_data`</ApiLink> method of the crawler to export the entire default dataset to a single file. This method supports exporting data in either CSV or JSON format and also accepts additional keyword arguments so you can fine-tune the underlying `json.dump` or `csv.writer` behavior.
|
||||
|
||||
:::note
|
||||
|
||||
For these examples, we are using the <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>. However, the same method is available for other crawlers as well. You can use it in exactly the same way.
|
||||
|
||||
:::
|
||||
|
||||
<Tabs groupId="main">
|
||||
<TabItem value="json" label="JSON">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{JsonExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
<TabItem value="csv" label="CSV">
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{CsvExample}
|
||||
</RunnableCodeBlock>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
id: fill-and-submit-web-form
|
||||
title: Fill and submit web form
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import RequestExample from '!!raw-loader!roa-loader!./code_examples/fill_and_submit_web_form_request.py';
|
||||
import CrawlerExample from '!!raw-loader!roa-loader!./code_examples/fill_and_submit_web_form_crawler.py';
|
||||
|
||||
This example demonstrates how to fill and submit a web form using the <ApiLink to="class/HttpCrawler">`HttpCrawler`</ApiLink> crawler. The same approach applies to any crawler that inherits from it, such as the <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink> or <ApiLink to="class/ParselCrawler">`ParselCrawler`</ApiLink>.
|
||||
|
||||
We are going to use the [httpbin.org](https://httpbin.org) website to demonstrate how it works.
|
||||
|
||||
## Investigate the form fields
|
||||
|
||||
First, we need to examine the form fields and the form's action URL. You can do this by opening the [httpbin.org/forms/post](https://httpbin.org/forms/post) page in a browser and inspecting the form fields.
|
||||
|
||||
In Chrome, right-click on the page and select "Inspect" or press `Ctrl+Shift+I`.
|
||||
Use the element selector (`Ctrl+Shift+C`) to click on the form element you want to inspect.
|
||||
|
||||

|
||||
|
||||
Identify the field names. For example, the customer name field is `custname`, the email field is `custemail`, and the phone field is `custtel`.
|
||||
|
||||
Now navigate to the "Network" tab in developer tools and submit the form by clicking the "Submit order" button.
|
||||
|
||||

|
||||
|
||||
Find the form submission request and examine its details. The "Headers" tab will show the submission URL, in this case, it is `https://httpbin.org/post`.
|
||||
|
||||

|
||||
|
||||
The "Payload" tab will display the form fields and their submitted values. This method could be an alternative to inspecting the HTML source code directly.
|
||||
|
||||

|
||||
|
||||
## Preparing a POST request
|
||||
|
||||
Now, let's create a POST request with the form fields and their values using the <ApiLink to="class/Request">`Request`</ApiLink> class, specifically its <ApiLink to="class/Request#from_url">`Request.from_url`</ApiLink> constructor:
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{RequestExample}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
Alternatively, you can send form data as URL parameters using the `url` argument. It depends on the form and how it is implemented. However, sending the data as a POST request body using the `payload` is generally a better approach.
|
||||
|
||||
## Implementing the crawler
|
||||
|
||||
Finally, let's implement the crawler and run it with the prepared request. Although we are using the <ApiLink to="class/HttpCrawler">`HttpCrawler`</ApiLink>, the process is the same for any crawler that inherits from it.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{CrawlerExample}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
## Running the crawler
|
||||
|
||||
Finally, run your crawler. Your logs should show something like this:
|
||||
|
||||
```plaintext
|
||||
...
|
||||
[crawlee.http_crawler._http_crawler] INFO Processing https://httpbin.org/post ...
|
||||
[crawlee.http_crawler._http_crawler] INFO Response: {
|
||||
"args": {},
|
||||
"data": "",
|
||||
"files": {},
|
||||
"form": {
|
||||
"comments": "Please ring the doorbell upon arrival.",
|
||||
"custemail": "johndoe@example.com",
|
||||
"custname": "John Doe",
|
||||
"custtel": "1234567890",
|
||||
"delivery": "13:00",
|
||||
"size": "large",
|
||||
"topping": [
|
||||
"bacon",
|
||||
"cheese",
|
||||
"mushroom"
|
||||
]
|
||||
},
|
||||
"headers": {
|
||||
"Accept": "*/*",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Content-Length": "190",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Host": "httpbin.org",
|
||||
"User-Agent": "python-httpx/0.27.0",
|
||||
"X-Amzn-Trace-Id": "Root=1-66c849d6-1ae432fb7b4156e6149ff37f"
|
||||
},
|
||||
"json": null,
|
||||
"origin": "78.80.81.196",
|
||||
"url": "https://httpbin.org/post"
|
||||
}
|
||||
|
||||
[crawlee._autoscaling.autoscaled_pool] INFO Waiting for remaining tasks to finish
|
||||
[crawlee.http_crawler._http_crawler] INFO Final request statistics:
|
||||
┌───────────────────────────────┬──────────┐
|
||||
│ requests_finished │ 1 │
|
||||
│ requests_failed │ 0 │
|
||||
│ retry_histogram │ [1] │
|
||||
│ request_avg_failed_duration │ None │
|
||||
│ request_avg_finished_duration │ 0.678442 │
|
||||
│ requests_finished_per_minute │ 85 │
|
||||
│ requests_failed_per_minute │ 0 │
|
||||
│ request_total_duration │ 0.678442 │
|
||||
│ requests_total │ 1 │
|
||||
│ crawler_runtime │ 0.707666 │
|
||||
└───────────────────────────────┴──────────┘
|
||||
```
|
||||
|
||||
This log output confirms that the crawler successfully submitted the form and processed the response. Congratulations! You have successfully filled and submitted a web form using the <ApiLink to="class/HttpCrawler">`HttpCrawler`</ApiLink>.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
id: configure-json-logging
|
||||
title: Сonfigure JSON logging
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import JsonLoggingExample from '!!raw-loader!roa-loader!./code_examples/configure_json_logging.py';
|
||||
|
||||
This example demonstrates how to configure JSON line (JSONL) logging with Crawlee. By using the `use_table_logs=False` parameter, you can disable table-formatted statistics logs, which makes it easier to parse logs with external tools or to serialize them as JSON.
|
||||
|
||||
The example shows how to integrate with the popular [`loguru`](https://github.com/delgan/loguru) library to capture Crawlee logs and format them as JSONL (one JSON object per line). This approach works well when you need to collect logs for analysis, monitoring, or when integrating with logging platforms like ELK Stack, Grafana Loki, or similar systems.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{JsonLoggingExample}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
Here's an example of what a crawler statistics log entry in JSONL format.
|
||||
|
||||
```json
|
||||
{
|
||||
"text": "[HttpCrawler] | INFO | - Final request statistics: {'requests_finished': 1, 'requests_failed': 0, 'retry_histogram': [1], 'request_avg_failed_duration': None, 'request_avg_finished_duration': 3.57098, 'requests_finished_per_minute': 17, 'requests_failed_per_minute': 0, 'request_total_duration': 3.57098, 'requests_total': 1, 'crawler_runtime': 3.59165}\n",
|
||||
"record": {
|
||||
"elapsed": { "repr": "0:00:05.604568", "seconds": 5.604568 },
|
||||
"exception": null,
|
||||
"extra": {
|
||||
"requests_finished": 1,
|
||||
"requests_failed": 0,
|
||||
"retry_histogram": [1],
|
||||
"request_avg_failed_duration": null,
|
||||
"request_avg_finished_duration": 3.57098,
|
||||
"requests_finished_per_minute": 17,
|
||||
"requests_failed_per_minute": 0,
|
||||
"request_total_duration": 3.57098,
|
||||
"requests_total": 1,
|
||||
"crawler_runtime": 3.59165
|
||||
},
|
||||
"file": {
|
||||
"name": "_basic_crawler.py",
|
||||
"path": "/crawlers/_basic/_basic_crawler.py"
|
||||
},
|
||||
"function": "run",
|
||||
"level": { "icon": "ℹ️", "name": "INFO", "no": 20 },
|
||||
"line": 583,
|
||||
"message": "Final request statistics:",
|
||||
"module": "_basic_crawler",
|
||||
"name": "HttpCrawler",
|
||||
"process": { "id": 198383, "name": "MainProcess" },
|
||||
"thread": { "id": 135312814966592, "name": "MainThread" },
|
||||
"time": {
|
||||
"repr": "2025-03-17 17:14:45.339150+00:00",
|
||||
"timestamp": 1742231685.33915
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
id: parsel-crawler
|
||||
title: Parsel crawler
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import ParselCrawlerExample from '!!raw-loader!roa-loader!./code_examples/parsel_crawler.py';
|
||||
|
||||
This example shows how to use <ApiLink to="class/ParselCrawler">`ParselCrawler`</ApiLink> to crawl a website or a list of URLs. Each URL is loaded using a plain HTTP request and the response is parsed using [Parsel](https://pypi.org/project/parsel/) library which supports CSS and XPath selectors for HTML responses and JMESPath for JSON responses. We can extract data from all kinds of complex HTML structures using XPath. In this example, we will use Parsel to crawl github.com and extract page title, URL and emails found in the webpage. The default handler will scrape data from the current webpage and enqueue all the links found in the webpage for continuous scraping. It also shows how you can add optional pre-navigation hook to the crawler. Pre-navigation hooks are user defined functions that execute before sending the request.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{ParselCrawlerExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
id: playwright-crawler
|
||||
title: Playwright crawler
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import PlaywrightCrawlerExample from '!!raw-loader!roa-loader!./code_examples/playwright_crawler.py';
|
||||
|
||||
This example demonstrates how to use <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> to recursively scrape the Hacker news website using headless Chromium and Playwright.
|
||||
|
||||
The <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> manages the browser and page instances, simplifying the process of interacting with web pages. In the request handler, Playwright's API is used to extract data from each post on the page. Specifically, it retrieves the title, rank, and URL of each post. Additionally, the handler enqueues links to the next pages to ensure continuous scraping. This setup is ideal for scraping dynamic web pages where JavaScript execution is required to render the content.
|
||||
|
||||
A **pre-navigation hook** can be used to perform actions before navigating to the URL. This hook provides further flexibility in controlling environment and preparing for navigation.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightCrawlerExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
id: adaptive-playwright-crawler
|
||||
title: Adaptive Playwright crawler
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import AdaptivePlaywrightCrawlerExample from '!!raw-loader!roa-loader!./code_examples/adaptive_playwright_crawler.py';
|
||||
|
||||
This example demonstrates how to use <ApiLink to="class/AdaptivePlaywrightCrawler">`AdaptivePlaywrightCrawler`</ApiLink>. An <ApiLink to="class/AdaptivePlaywrightCrawler">`AdaptivePlaywrightCrawler`</ApiLink> is a combination of <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and some implementation of HTTP-based crawler such as <ApiLink to="class/ParselCrawler">`ParselCrawler`</ApiLink> or <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>.
|
||||
It uses a more limited crawling context interface so that it is able to switch to HTTP-only crawling when it detects that it may bring a performance benefit.
|
||||
|
||||
A [pre-navigation hook](/python/docs/guides/adaptive-playwright-crawler#page-configuration-with-pre-navigation-hooks) can be used to perform actions before navigating to the URL. This hook provides further flexibility in controlling environment and preparing for navigation. Hooks will be executed both for the pages crawled by HTTP-bases sub crawler and playwright based sub crawler. Use `playwright_only=True` to mark hooks that should be executed only for playwright sub crawler.
|
||||
|
||||
For more detailed description please see [Adaptive Playwright crawler guide](/python/docs/guides/adaptive-playwright-crawler)
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{AdaptivePlaywrightCrawlerExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
id: playwright-crawler-with-block-requests
|
||||
title: Playwright crawler with block requests
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import PlaywrightBlockRequests from '!!raw-loader!roa-loader!./code_examples/playwright_block_requests.py';
|
||||
|
||||
This example demonstrates how to optimize your <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> performance by blocking unnecessary network requests.
|
||||
|
||||
The primary use case is when you need to scrape or interact with web pages without loading non-essential resources like images, styles, or analytics scripts. This can significantly reduce bandwidth usage and improve crawling speed.
|
||||
|
||||
The <ApiLink to="class/BlockRequestsFunction">`block_requests`</ApiLink> helper provides the most efficient way to block requests as it operates directly in the browser.
|
||||
|
||||
By default, <ApiLink to="class/BlockRequestsFunction">`block_requests`</ApiLink> will block all URLs including the following patterns:
|
||||
|
||||
```python
|
||||
['.css', '.webp', '.jpg', '.jpeg', '.png', '.svg', '.gif', '.woff', '.pdf', '.zip']
|
||||
```
|
||||
|
||||
You can also replace the default patterns list with your own by providing `url_patterns`, or extend it by passing additional patterns in `extra_url_patterns`.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightBlockRequests}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
id: playwright-crawler-with-camoufox
|
||||
title: Playwright crawler with Camoufox
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import PlaywrightCrawlerExampleWithCamoufox from '!!raw-loader!roa-loader!./code_examples/playwright_crawler_with_camoufox.py';
|
||||
|
||||
This example demonstrates how to integrate Camoufox into <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> using <ApiLink to="class/BrowserPool">`BrowserPool`</ApiLink> with custom <ApiLink to="class/PlaywrightBrowserPlugin">`PlaywrightBrowserPlugin`</ApiLink>.
|
||||
|
||||
Camoufox is a stealthy minimalistic build of Firefox. For details please visit its homepage https://camoufox.com/ .
|
||||
To be able to run this example you will need to install camoufox, as it is external tool, and it is not part of the crawlee. For installation please see https://pypi.org/project/camoufox/.
|
||||
|
||||
**Warning!** Camoufox is using custom build of firefox. This build can be hundreds of MB large.
|
||||
You can either pre-download this file using following command `python3 -m camoufox fetch` or camoufox will download it automatically once you try to run it, and it does not find existing binary.
|
||||
For more details please refer to: https://github.com/daijro/camoufox/tree/main/pythonlib#camoufox-python-interface
|
||||
|
||||
**Project template -** It is possible to generate project with Python code which includes Camoufox integration into crawlee through crawlee cli. Call `crawlee create` and pick `Playwright-camoufox` when asked for Crawler type.
|
||||
|
||||
The example code after PlayWrightCrawler instantiation is similar to example describing the use of Playwright Crawler. The main difference is that in this example Camoufox will be used as the browser through BrowserPool.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightCrawlerExampleWithCamoufox}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
id: playwright-crawler-with-fingerprint-generator
|
||||
title: Playwright crawler with fingerprint generator
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import PlaywrightCrawlerExample from '!!raw-loader!roa-loader!./code_examples/playwright_crawler_with_fingerprint_generator.py';
|
||||
|
||||
This example demonstrates how to use <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> together with <ApiLink to="class/FingerprintGenerator">`FingerprintGenerator`</ApiLink> that will populate several browser attributes to mimic real browser fingerprint. To read more about fingerprints please see: https://docs.apify.com/academy/anti-scraping/techniques/fingerprinting.
|
||||
|
||||
You can implement your own fingerprint generator or use <ApiLink to="class/BrowserforgeFingerprintGenerator">`DefaultFingerprintGenerator`</ApiLink>. To use the generator initialize it with the desired fingerprint options. The generator will try to create fingerprint based on those options. Unspecified options will be automatically selected by the generator from the set of reasonable values. If some option is important for you, do not rely on the default and explicitly define it.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightCrawlerExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
id: respect-robots-txt-file
|
||||
title: Respect robots.txt file
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import RespectRobotsTxt from '!!raw-loader!roa-loader!./code_examples/respect_robots_txt_file.py';
|
||||
import OnSkippedRequest from '!!raw-loader!roa-loader!./code_examples/respect_robots_on_skipped_request.py';
|
||||
|
||||
This example demonstrates how to configure your crawler to respect the rules established by websites for crawlers as described in the [robots.txt](https://www.robotstxt.org/robotstxt.html) file.
|
||||
|
||||
To configure `Crawlee` to follow the `robots.txt` file, set the parameter `respect_robots_txt_file=True` in <ApiLink to="class/BasicCrawlerOptions">`BasicCrawlerOptions`</ApiLink>. In this case, `Crawlee` will skip any URLs forbidden in the website's robots.txt file.
|
||||
|
||||
As an example, let's look at the website `https://news.ycombinator.com/` and its corresponding [robots.txt](https://news.ycombinator.com/robots.txt) file. Since the file has a rule `Disallow: /login`, the URL `https://news.ycombinator.com/login` will be automatically skipped.
|
||||
|
||||
The code below demonstrates this behavior using the <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>:
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{RespectRobotsTxt}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
## Handle with `on_skipped_request`
|
||||
|
||||
If you want to process URLs skipped according to the `robots.txt` rules, for example for further analysis, you should use the `on_skipped_request` handler from <ApiLink to="class/BasicCrawler#on_skipped_request">`BasicCrawler`</ApiLink>.
|
||||
|
||||
Let's update the code by adding the `on_skipped_request` handler:
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{OnSkippedRequest}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
id: resuming-paused-crawl
|
||||
title: Resuming a paused crawl
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import ResumeCrawl from '!!raw-loader!roa-loader!./code_examples/resuming_paused_crawl.py';
|
||||
|
||||
This example demonstrates how to resume crawling from its last state when running locally, if for some reason it was unexpectedly terminated.
|
||||
|
||||
If each run should continue crawling from the previous state, you can configure this using `purge_on_start` in <ApiLink to="class/Configuration">`Configuration`</ApiLink>.
|
||||
|
||||
Use the code below and perform 2 sequential runs. During the 1st run, stop the crawler by pressing `CTRL+C`, and the 2nd run will resume crawling from where it stopped.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{ResumeCrawl}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
Perform the 1st run, interrupting the crawler with `CTRL+C` after 2 links have been processed.
|
||||
|
||||

|
||||
|
||||
Now resume crawling after the pause to process the remaining 3 links.
|
||||
|
||||

|
||||
|
||||
Alternatively, use the environment variable `CRAWLEE_PURGE_ON_START=0` instead of using `configuration.purge_on_start = False`.
|
||||
|
||||
For example, when running code:
|
||||
|
||||
```bash
|
||||
CRAWLEE_PURGE_ON_START=0 python -m best_crawler
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
id: run-parallel-crawlers
|
||||
title: Run parallel crawlers
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import RunParallelCrawlersExample from '!!raw-loader!roa-loader!./code_examples/run_parallel_crawlers.py';
|
||||
|
||||
This example demonstrates how to run two parallel crawlers where one crawler processes links discovered by another crawler.
|
||||
|
||||
In some situations, you may need different approaches for scraping data from a website. For example, you might use <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> for navigating JavaScript-heavy pages and a faster, more lightweight <ApiLink to="class/ParselCrawler">`ParselCrawler`</ApiLink> for processing static pages. One way to solve this is to use <ApiLink to="class/AdaptivePlaywrightCrawler">`AdaptivePlaywrightCrawler`</ApiLink>, see the [Adaptive Playwright crawler example](./adaptive-playwright-crawler) to learn more.
|
||||
|
||||
The code below demonstrates an alternative approach using two separate crawlers. Links are passed between crawlers via <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> aliases. The `keep_alive` option allows the Playwright crawler to run in the background and wait for incoming links without stopping when its queue is empty. You can also use different storage clients for each crawler without losing the ability to pass links between queues. Learn more about available storage clients in this [guide](/python/docs/guides/storage-clients).
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{RunParallelCrawlersExample}
|
||||
</RunnableCodeBlock>
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
id: using_browser_profile
|
||||
title: Using browser profile
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
|
||||
import ChromeProfileExample from '!!raw-loader!./code_examples/using_browser_profiles_chrome.py';
|
||||
import FirefoxProfileExample from '!!raw-loader!./code_examples/using_browser_profiles_firefox.py';
|
||||
|
||||
This example demonstrates how to run <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> using your local browser profile from [Chrome](https://www.google.com/intl/us/chrome/) or [Firefox](https://www.firefox.com/).
|
||||
|
||||
Using browser profiles allows you to leverage existing login sessions, saved passwords, bookmarks, and other personalized browser data during crawling. This can be particularly useful for testing scenarios or when you need to access content that requires authentication.
|
||||
|
||||
## Chrome browser
|
||||
|
||||
To run <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> with your Chrome profile, you need to know the path to your profile files. You can find this information by entering `chrome://version/` as a URL in your Chrome browser. If you have multiple profiles, pay attention to the profile name - if you only have one profile, it's always `Default`.
|
||||
|
||||
:::warning Profile access limitation
|
||||
Due to [Chrome's security policies](https://developer.chrome.com/blog/remote-debugging-port), automation cannot use your main browsing profile directly. The example copies your profile to a temporary location as a workaround.
|
||||
:::
|
||||
|
||||
Make sure you don't have any running Chrome browser processes before running this code:
|
||||
|
||||
<CodeBlock className="language-python" language="python">
|
||||
{ChromeProfileExample}
|
||||
</CodeBlock>
|
||||
|
||||
## Firefox browser
|
||||
|
||||
To find the path to your Firefox profile, enter `about:profiles` as a URL in your Firefox browser. Unlike Chrome, you can use your standard profile path directly without copying it first.
|
||||
|
||||
Make sure you don't have any running Firefox browser processes before running this code:
|
||||
|
||||
<CodeBlock className="language-python" language="python">
|
||||
{FirefoxProfileExample}
|
||||
</CodeBlock>
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
id: using-sitemap-request-loader
|
||||
title: Using sitemap request loader
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import SitemapRequestLoaderExample from '!!raw-loader!roa-loader!./code_examples/using_sitemap_request_loader.py';
|
||||
|
||||
This example demonstrates how to use <ApiLink to="class/SitemapRequestLoader">`SitemapRequestLoader`</ApiLink> to crawl websites that provide `sitemap.xml` files following the [Sitemaps protocol](https://www.sitemaps.org/protocol.html). The <ApiLink to="class/SitemapRequestLoader">`SitemapRequestLoader`</ApiLink> processes sitemaps in a streaming fashion without loading them entirely into memory, making it suitable for large sitemaps.
|
||||
|
||||
The example shows how to use the `transform_request_function` parameter to configure request options based on URL patterns. This allows you to modify request properties such as labels and user data based on the source URL, enabling different handling logic for different websites or sections.
|
||||
|
||||
The following code example implements processing of sitemaps from two different domains (Apify and Crawlee), with different labels assigned to requests based on their host. The `create_transform_request` function maps each host to the corresponding request configuration, while the crawler uses different handlers based on the assigned labels.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{SitemapRequestLoaderExample}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
For more information about request loaders, see the [Request loaders guide](../guides/request-loaders).
|
||||
@@ -0,0 +1,428 @@
|
||||
---
|
||||
id: architecture-overview
|
||||
title: Architecture overview
|
||||
description: An overview of the core components of the Crawlee library and its architecture.
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
|
||||
Crawlee is a modern and modular web scraping framework. It is designed for both HTTP-only and browser-based scraping. In this guide, we will provide a high-level overview of its architecture and the main components that make up the system.
|
||||
|
||||
## Crawler
|
||||
|
||||
The main user-facing component of Crawlee is the crawler, which orchestrates the crawling process and takes care of all other components. It manages storages, executes user-defined request handlers, handles retries, manages concurrency, and coordinates all other components. All crawlers inherit from the <ApiLink to="class/BasicCrawler">`BasicCrawler`</ApiLink> class, which provides the basic functionality. There are two main groups of specialized crawlers: HTTP crawlers and browser crawlers.
|
||||
|
||||
:::info
|
||||
|
||||
You will learn more about the request handlers in the request router section.
|
||||
|
||||
:::
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
class:
|
||||
hideEmptyMembersBox: true
|
||||
---
|
||||
|
||||
classDiagram
|
||||
|
||||
%% ========================
|
||||
%% Abstract classes
|
||||
%% ========================
|
||||
|
||||
class BasicCrawler {
|
||||
<<abstract>>
|
||||
}
|
||||
|
||||
class AbstractHttpCrawler {
|
||||
<<abstract>>
|
||||
}
|
||||
|
||||
%% ========================
|
||||
%% Specific classes
|
||||
%% ========================
|
||||
|
||||
class HttpCrawler
|
||||
|
||||
class ParselCrawler
|
||||
|
||||
class BeautifulSoupCrawler
|
||||
|
||||
class PlaywrightCrawler
|
||||
|
||||
class AdaptivePlaywrightCrawler
|
||||
|
||||
class StagehandCrawler
|
||||
|
||||
%% ========================
|
||||
%% Inheritance arrows
|
||||
%% ========================
|
||||
|
||||
BasicCrawler --|> AbstractHttpCrawler
|
||||
BasicCrawler --|> PlaywrightCrawler
|
||||
BasicCrawler --|> AdaptivePlaywrightCrawler
|
||||
AbstractHttpCrawler --|> HttpCrawler
|
||||
AbstractHttpCrawler --|> ParselCrawler
|
||||
AbstractHttpCrawler --|> BeautifulSoupCrawler
|
||||
PlaywrightCrawler --|> StagehandCrawler
|
||||
```
|
||||
|
||||
### HTTP crawlers
|
||||
|
||||
HTTP crawlers use HTTP clients to fetch pages and parse them with HTML parsing libraries. They are fast and efficient for sites that do not require JavaScript rendering. HTTP clients are Crawlee components that wrap around HTTP libraries like [httpx](https://www.python-httpx.org/), [curl-impersonate](https://github.com/lwthiker/curl-impersonate) or [impit](https://apify.github.io/impit) and handle HTTP communication for requests and responses. You can learn more about them in the [HTTP clients guide](./http-clients).
|
||||
|
||||
HTTP crawlers inherit from <ApiLink to="class/AbstractHttpCrawler">`AbstractHttpCrawler`</ApiLink> and there are three crawlers that belong to this category:
|
||||
|
||||
- <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink> utilizes the [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/) HTML parser.
|
||||
- <ApiLink to="class/ParselCrawler">`ParselCrawler`</ApiLink> utilizes [Parsel](https://github.com/scrapy/parsel) for parsing HTML.
|
||||
- <ApiLink to="class/HttpCrawler">`HttpCrawler`</ApiLink> does not parse HTTP responses at all and is used when no content parsing is required.
|
||||
|
||||
You can learn more about HTTP crawlers in the [HTTP crawlers guide](./http-crawlers).
|
||||
|
||||
### Browser crawlers
|
||||
|
||||
Browser crawlers use a real browser to render pages, enabling scraping of sites that require JavaScript. They manage browser instances, pages, and context lifecycles. Crawlee provides two browser crawlers:
|
||||
|
||||
- <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> utilizes the [Playwright](https://playwright.dev/) library and provides a high-level API for controlling and navigating browsers. You can learn more about it in the [Playwright crawler guide](./playwright-crawler).
|
||||
- <ApiLink to="class/StagehandCrawler">`StagehandCrawler`</ApiLink> extends `PlaywrightCrawler` with AI-powered browser automation via [Stagehand](https://github.com/browserbase/stagehand). It adds natural-language methods (`act`, `extract`, `observe`, `execute`) directly on the page object. You can learn more about it in the [Stagehand crawler guide](./stagehand-crawler).
|
||||
|
||||
### Adaptive crawler
|
||||
|
||||
The <ApiLink to="class/AdaptivePlaywrightCrawler">`AdaptivePlaywrightCrawler`</ApiLink> sits between HTTP and browser crawlers. It can automatically decide whether to use HTTP or browser crawling for each request based on heuristics or user configuration. This allows for optimal performance and compatibility. It also provides a uniform interface for both crawling types (modes). You can learn more about adaptive crawling in the [Adaptive Playwright crawler guide](./adaptive-playwright-crawler).
|
||||
|
||||
## Crawling contexts
|
||||
|
||||
Crawling contexts are objects that encapsulate the state and data for each request being processed by the crawler. They provide access to the request, response, session, and helper methods for handling the request. Crawling contexts are used to pass data between different parts of the crawler and to manage the lifecycle of each request. These contexts are provided to user-defined request handlers, which can then use them to access request data, response data, or use helper methods to interact with storages, and extract and enqueue new requests.
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
class:
|
||||
hideEmptyMembersBox: true
|
||||
---
|
||||
|
||||
classDiagram
|
||||
|
||||
%% ========================
|
||||
%% Classes
|
||||
%% ========================
|
||||
|
||||
class BasicCrawlingContext
|
||||
|
||||
class HttpCrawlingContext
|
||||
|
||||
class HttpCrawlingResult
|
||||
|
||||
class ParsedHttpCrawlingContext
|
||||
|
||||
class ParselCrawlingContext
|
||||
|
||||
class BeautifulSoupCrawlingContext
|
||||
|
||||
class PlaywrightPreNavCrawlingContext
|
||||
|
||||
class PlaywrightCrawlingContext
|
||||
|
||||
class AdaptivePlaywrightPreNavCrawlingContext
|
||||
|
||||
class AdaptivePlaywrightCrawlingContext
|
||||
|
||||
class StagehandPreNavCrawlingContext
|
||||
|
||||
class StagehandPostNavCrawlingContext
|
||||
|
||||
class StagehandCrawlingContext
|
||||
|
||||
%% ========================
|
||||
%% Inheritance arrows
|
||||
%% ========================
|
||||
|
||||
BasicCrawlingContext --|> HttpCrawlingContext
|
||||
|
||||
HttpCrawlingResult --|> HttpCrawlingContext
|
||||
|
||||
HttpCrawlingContext --|> ParsedHttpCrawlingContext
|
||||
|
||||
ParsedHttpCrawlingContext --|> ParselCrawlingContext
|
||||
|
||||
ParsedHttpCrawlingContext --|> BeautifulSoupCrawlingContext
|
||||
|
||||
BasicCrawlingContext --|> PlaywrightPreNavCrawlingContext
|
||||
|
||||
PlaywrightPreNavCrawlingContext --|> PlaywrightCrawlingContext
|
||||
|
||||
BasicCrawlingContext --|> AdaptivePlaywrightPreNavCrawlingContext
|
||||
|
||||
ParsedHttpCrawlingContext --|> AdaptivePlaywrightCrawlingContext
|
||||
|
||||
PlaywrightPreNavCrawlingContext --|> StagehandPreNavCrawlingContext
|
||||
|
||||
StagehandPreNavCrawlingContext --|> StagehandPostNavCrawlingContext
|
||||
|
||||
StagehandPostNavCrawlingContext --|> StagehandCrawlingContext
|
||||
```
|
||||
|
||||
They have a similar inheritance structure as the crawlers, with the base class being <ApiLink to="class/BasicCrawlingContext">`BasicCrawlingContext`</ApiLink>. The specific crawling contexts are:
|
||||
- <ApiLink to="class/HttpCrawlingContext">`HttpCrawlingContext`</ApiLink> for HTTP crawlers.
|
||||
- <ApiLink to="class/ParsedHttpCrawlingContext">`ParsedHttpCrawlingContext`</ApiLink> for HTTP crawlers with parsed responses.
|
||||
- <ApiLink to="class/ParselCrawlingContext">`ParselCrawlingContext`</ApiLink> for HTTP crawlers that use [Parsel](https://github.com/scrapy/parsel) for parsing.
|
||||
- <ApiLink to="class/BeautifulSoupCrawlingContext">`BeautifulSoupCrawlingContext`</ApiLink> for HTTP crawlers that use [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/) for parsing.
|
||||
- <ApiLink to="class/PlaywrightPreNavCrawlingContext">`PlaywrightPreNavCrawlingContext`</ApiLink> for Playwright crawlers before the page is navigated.
|
||||
- <ApiLink to="class/PlaywrightCrawlingContext">`PlaywrightCrawlingContext`</ApiLink> for Playwright crawlers.
|
||||
- <ApiLink to="class/AdaptivePlaywrightPreNavCrawlingContext">`AdaptivePlaywrightPreNavCrawlingContext`</ApiLink> for Adaptive Playwright crawlers before the page is navigated.
|
||||
- <ApiLink to="class/AdaptivePlaywrightCrawlingContext">`AdaptivePlaywrightCrawlingContext`</ApiLink> for Adaptive Playwright crawlers.
|
||||
- <ApiLink to="class/StagehandPreNavCrawlingContext">`StagehandPreNavCrawlingContext`</ApiLink> for Stagehand crawlers before the page is navigated.
|
||||
- <ApiLink to="class/StagehandPostNavCrawlingContext">`StagehandPostNavCrawlingContext`</ApiLink> for Stagehand crawlers after the page is navigated.
|
||||
- <ApiLink to="class/StagehandCrawlingContext">`StagehandCrawlingContext`</ApiLink> for Stagehand crawlers.
|
||||
|
||||
## Storages
|
||||
|
||||
Storages are the components that manage data in Crawlee. They provide a way to store and retrieve data during the crawling process. Crawlee's storage system consists of two main layers:
|
||||
|
||||
- **Storages**: High-level interfaces for interacting with different storage types
|
||||
- **Storage clients**: Backend implementations that handle the actual data persistence and management (you will learn more about them in the next section)
|
||||
|
||||
Crawlee provides three built-in storage types for managing data:
|
||||
|
||||
- <ApiLink to="class/Dataset">`Dataset`</ApiLink> - Append-only, tabular storage for structured data. It is ideal for storing scraping results.
|
||||
- <ApiLink to="class/KeyValueStore">`KeyValueStore`</ApiLink> - Storage for arbitrary data like JSON documents, images or configs. It supports get and set operations with key-value pairs; updates are only possible by replacement.
|
||||
- <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> - A managed queue for pending and completed requests, with automatic deduplication and dynamic addition of new items. It is used to track URLs for crawling.
|
||||
|
||||
See the [Storages guide](./storages) for more details.
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
class:
|
||||
hideEmptyMembersBox: true
|
||||
---
|
||||
|
||||
classDiagram
|
||||
|
||||
%% ========================
|
||||
%% Abstract classes
|
||||
%% ========================
|
||||
|
||||
class Storage {
|
||||
<<abstract>>
|
||||
}
|
||||
|
||||
%% ========================
|
||||
%% Specific classes
|
||||
%% ========================
|
||||
|
||||
class Dataset
|
||||
|
||||
class KeyValueStore
|
||||
|
||||
class RequestQueue
|
||||
|
||||
%% ========================
|
||||
%% Inheritance arrows
|
||||
%% ========================
|
||||
|
||||
Storage --|> Dataset
|
||||
Storage --|> KeyValueStore
|
||||
Storage --|> RequestQueue
|
||||
```
|
||||
|
||||
## Storage clients
|
||||
|
||||
Storage clients are the backend implementations for storages that handle interactions with different storage systems. They provide a unified interface for <ApiLink to="class/Dataset">`Dataset`</ApiLink>, <ApiLink to="class/KeyValueStore">`KeyValueStore`</ApiLink>, and <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink>, regardless of the underlying storage implementation.
|
||||
|
||||
Crawlee provides several built-in storage client implementations:
|
||||
|
||||
- <ApiLink to="class/MemoryStorageClient">`MemoryStorageClient`</ApiLink> - Stores data in memory with no persistence (ideal for testing and fast operations).
|
||||
- <ApiLink to="class/FileSystemStorageClient">`FileSystemStorageClient`</ApiLink> - Provides persistent file system storage with caching (default client).
|
||||
- [`ApifyStorageClient`](https://docs.apify.com/sdk/python/reference/class/ApifyStorageClient) - Manages storage on the [Apify platform](https://apify.com/) (cloud-based). It is implemented in the [Apify SDK](https://github.com/apify/apify-sdk-python). You can find more information about it in the [Apify SDK documentation](https://docs.apify.com/sdk/python/docs/overview/introduction).
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
class:
|
||||
hideEmptyMembersBox: true
|
||||
---
|
||||
|
||||
classDiagram
|
||||
|
||||
%% ========================
|
||||
%% Abstract classes
|
||||
%% ========================
|
||||
|
||||
class StorageClient {
|
||||
<<abstract>>
|
||||
}
|
||||
|
||||
%% ========================
|
||||
%% Specific classes
|
||||
%% ========================
|
||||
|
||||
class MemoryStorageClient
|
||||
|
||||
class FileSystemStorageClient
|
||||
|
||||
class ApifyStorageClient
|
||||
|
||||
%% ========================
|
||||
%% Inheritance arrows
|
||||
%% ========================
|
||||
|
||||
StorageClient --|> MemoryStorageClient
|
||||
StorageClient --|> FileSystemStorageClient
|
||||
StorageClient --|> ApifyStorageClient
|
||||
```
|
||||
|
||||
Storage clients can be registered globally with the <ApiLink to="class/ServiceLocator">`ServiceLocator`</ApiLink> (you will learn more about the <ApiLink to="class/ServiceLocator">`ServiceLocator`</ApiLink> in the next section), passed directly to crawlers, or specified when opening individual storage instances. You can also create custom storage clients by implementing the <ApiLink to="class/StorageClient">`StorageClient`</ApiLink> interface.
|
||||
|
||||
See the [Storage clients guide](./storage-clients) for more details.
|
||||
|
||||
## Request router
|
||||
|
||||
The request <ApiLink to="class/Router">`Router`</ApiLink> is a central component that manages the flow of requests and responses in Crawlee. It is responsible for routing requests to the appropriate request handlers, managing the crawling context, and coordinating the execution of user-defined logic.
|
||||
|
||||
### Request handlers
|
||||
|
||||
Request handlers are user-defined functions that process requests and responses in Crawlee. They are the core of the crawling logic and are responsible for handling data extraction, processing, and storage. Each request handler receives a crawling context as an argument, which provides access to request data, response data, and other information related to the request. Request handlers can be registered with the <ApiLink to="class/Router">`Router`</ApiLink>.
|
||||
|
||||
The request routing in Crawlee supports:
|
||||
- Default handlers - Fallback handlers for requests without specific labels.
|
||||
- Label-based routing - Handlers for specific request types based on labels.
|
||||
- Error handlers - Handle errors during request processing.
|
||||
- Failed request handlers - Handle requests that exceed retry limits.
|
||||
- Pre-navigation hooks - Execute logic before navigating to URLs.
|
||||
|
||||
See the [Request router guide](./request-router) for detailed information and examples.
|
||||
|
||||
## Service locator
|
||||
|
||||
The <ApiLink to="class/ServiceLocator">`ServiceLocator`</ApiLink> is a central registry for global services in Crawlee. It manages and provides access to core services throughout the framework, ensuring consistent configuration across all components. The service locator coordinates these three services:
|
||||
|
||||
- <ApiLink to="class/Configuration">`Configuration`</ApiLink> - Application-wide settings and parameters that control various aspects of Crawlee behavior.
|
||||
- <ApiLink to="class/StorageClient">`StorageClient`</ApiLink> - Backend implementation for data storage across datasets, key-value stores, and request queues.
|
||||
- <ApiLink to="class/EventManager">`EventManager`</ApiLink> - Event coordination system for internal framework events and custom user hooks.
|
||||
|
||||
Services can be registered globally through the `service_locator` singleton instance, passed to crawler constructors, or provided when opening individual storage instances. The service locator includes conflict prevention mechanisms to ensure configuration consistency and prevent accidental service conflicts during runtime.
|
||||
|
||||
See the [Service locator guide](./service-locator) for detailed information about service registration and configuration options.
|
||||
|
||||
## Request loaders
|
||||
|
||||
Request loaders provide a subset of <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> functionality, focusing specifically on reading and accessing streams of requests from various sources. They define how requests are fetched and processed, enabling use cases such as reading URLs from files, external APIs, sitemaps, or combining multiple sources together. Unlike request queues, they do not handle storage or persistence—they only provide request reading capabilities.
|
||||
|
||||
- <ApiLink to="class/RequestLoader">`RequestLoader`</ApiLink> - Base interface for read-only access to a stream of requests, with capabilities like fetching the next request, marking as handled, and status checking.
|
||||
- <ApiLink to="class/RequestList">`RequestList`</ApiLink> - Lightweight in-memory implementation of `RequestLoader` for managing static lists of URLs.
|
||||
- <ApiLink to="class/SitemapRequestLoader">`SitemapRequestLoader`</ApiLink> - A specialized loader that reads URLs from XML and plain-text sitemaps following the [Sitemaps protocol](https://www.sitemaps.org/protocol.html) with filtering capabilities.
|
||||
|
||||
### Request managers
|
||||
|
||||
<ApiLink to="class/RequestManager">`RequestManager`</ApiLink> extends <ApiLink to="class/RequestLoader">`RequestLoader`</ApiLink> with write capabilities for adding and reclaiming requests, providing full request management functionality. <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> is the primary concrete implementation of <ApiLink to="class/RequestManager">`RequestManager`</ApiLink>.
|
||||
|
||||
<ApiLink to="class/RequestManagerTandem">`RequestManagerTandem`</ApiLink> combines a read-only `RequestLoader` with a writable <ApiLink to="class/RequestManager">`RequestManager`</ApiLink>, transferring requests from the loader to the manager for hybrid scenarios. This is useful when you want to start with a predefined set of URLs (from a file or sitemap) but also need to add new requests dynamically during crawling. The tandem first processes all requests from the loader, then handles any additional requests added to the manager.
|
||||
|
||||
Request loaders are useful when you need to start with a predefined set of URLs. The tandem approach allows processing requests from static sources (like files or sitemaps) while maintaining the ability to add new requests dynamically.
|
||||
|
||||
See the [Request loaders guide](./request-loaders) for detailed information.
|
||||
|
||||
## Event manager
|
||||
|
||||
The <ApiLink to="class/EventManager">`EventManager`</ApiLink> is responsible for coordinating internal events throughout Crawlee and enabling custom hooks. It provides a system for registering event listeners, emitting events, and managing their execution lifecycle.
|
||||
|
||||
Crawlee provides several implementations of the event manager:
|
||||
|
||||
- <ApiLink to="class/EventManager">`EventManager`</ApiLink> is the base class for event management in Crawlee.
|
||||
- <ApiLink to="class/LocalEventManager">`LocalEventManager`</ApiLink> extends the base event manager for local environments by automatically emitting `SYSTEM_INFO` events at regular intervals. This provides real-time system metrics including CPU usage and memory consumption, which are essential for internal components like the <ApiLink to="class/Snapshotter">`Snapshotter`</ApiLink> and <ApiLink to="class/AutoscaledPool">`AutoscaledPool`</ApiLink>.
|
||||
- [`ApifyEventManager`](https://docs.apify.com/sdk/python/reference/class/PlatformEventManager) - Manages events on the [Apify platform](https://apify.com/) (cloud-based). It is implemented in the [Apify SDK](https://docs.apify.com/sdk/python/).
|
||||
|
||||
:::info
|
||||
|
||||
You can learn more about <ApiLink to="class/Snapshotter">`Snapshotter`</ApiLink> and <ApiLink to="class/AutoscaledPool">`AutoscaledPool`</ApiLink> and their configuration in the [Scaling crawlers guide](./scaling-crawlers).
|
||||
|
||||
:::
|
||||
|
||||
Crawlee defines several built-in event types:
|
||||
|
||||
- `PERSIST_STATE` - Emitted periodically to trigger state persistence.
|
||||
- `SYSTEM_INFO` - Contains CPU and memory usage information.
|
||||
- `MIGRATING` - Signals that the crawler is migrating to a different environment.
|
||||
- `ABORTING` - Indicates the crawler is aborting execution.
|
||||
- `EXIT` - Emitted when the crawler is exiting.
|
||||
- `CRAWLER_STATUS` - Provides status updates from crawlers.
|
||||
|
||||
Additional specialized events for browser and session management are also available.
|
||||
|
||||
The event manager operates as an async context manager, automatically starting periodic tasks when entered and ensuring all listeners complete before exiting. Event listeners can be either synchronous or asynchronous functions and are executed safely without blocking the main event loop.
|
||||
|
||||
```mermaid
|
||||
---
|
||||
config:
|
||||
class:
|
||||
hideEmptyMembersBox: true
|
||||
---
|
||||
|
||||
classDiagram
|
||||
|
||||
%% ========================
|
||||
%% Abstract classes
|
||||
%% ========================
|
||||
|
||||
class EventManager {
|
||||
<<abstract>>
|
||||
}
|
||||
|
||||
%% ========================
|
||||
%% Specific classes
|
||||
%% ========================
|
||||
|
||||
class LocalEventManager
|
||||
|
||||
class ApifyEventManager
|
||||
|
||||
%% ========================
|
||||
%% Inheritance arrows
|
||||
%% ========================
|
||||
|
||||
EventManager --|> LocalEventManager
|
||||
EventManager --|> ApifyEventManager
|
||||
```
|
||||
|
||||
## Session management
|
||||
|
||||
The core component of session management in Crawlee is <ApiLink to="class/SessionPool">`SessionPool`</ApiLink>. It manages a collection of sessions that simulate individual users with unique attributes like cookies, IP addresses (via proxies), and browser fingerprints. Sessions help avoid blocking by rotating user identities and maintaining realistic browsing patterns.
|
||||
|
||||
:::info
|
||||
|
||||
You can learn more about fingerprints and how to avoid getting blocked in the [Avoid blocking guide](./avoid-blocking).
|
||||
|
||||
:::
|
||||
|
||||
### Session
|
||||
|
||||
A session is represented as a <ApiLink to="class/Session">`Session`</ApiLink> object, which contains components like cookies, error tracking, usage limits, and expiration handling. Sessions can be marked as good (<ApiLink to="class/Session#mark_good">`Session.mark_good`</ApiLink>), bad (<ApiLink to="class/Session#mark_bad">`Session.mark_bad`</ApiLink>), or retired (<ApiLink to="class/Session#retire">`Session.retire`</ApiLink>) based on their performance, and they automatically become unusable when they exceed error thresholds or usage limits.
|
||||
|
||||
### Session pool
|
||||
|
||||
The session pool provides automated session lifecycle management:
|
||||
|
||||
- Automatic rotation - Retrieves random sessions from the pool and creates new ones as needed.
|
||||
- Pool maintenance - Removes retired sessions and maintains the pool at maximum capacity.
|
||||
- State persistence - Persists session state to enable recovery across restarts.
|
||||
- Configurable limits - Supports custom pool sizes, session settings, and creation functions.
|
||||
|
||||
The pool operates as an async context manager, automatically initializing with sessions and cleaning up on exit. It ensures proper session management by rotating sessions based on usage count, expiration time, and custom rules while maintaining optimal pool size.
|
||||
|
||||
See the [Session management guide](./session-management) for more information.
|
||||
|
||||
## Statistics
|
||||
|
||||
The <ApiLink to="class/Statistics">`Statistics`</ApiLink> class provides runtime monitoring for crawler operations, tracking performance metrics like request counts, processing times, retry attempts, and error patterns. It operates as an async context manager, automatically persisting data across crawler restarts and migrations using <ApiLink to="class/KeyValueStore">`KeyValueStore`</ApiLink>.
|
||||
|
||||
The system includes error tracking through the <ApiLink to="class/ErrorTracker">`ErrorTracker`</ApiLink> class, which groups similar errors by type and message patterns using wildcard matching. It can capture HTML snapshots and screenshots for debugging and separately track retry-specific errors.
|
||||
|
||||
Statistics are logged at configurable intervals in both table and inline formats, with final summary data returned from the `crawler.run` method available through <ApiLink to="class/FinalStatistics">`FinalStatistics`</ApiLink>.
|
||||
|
||||
## Conclusion
|
||||
|
||||
In this guide, we provided a high-level overview of the core components of the Crawlee library and its architecture. We covered the main components like crawlers, crawling contexts, storages, request routers, service locator, request loaders, event manager, session management, and statistics. Check out other guides, the [API reference](https://crawlee.dev/python/api), and [Examples](../examples) for more details on how to use these components in your own projects.
|
||||
|
||||
If you have questions or need assistance, feel free to reach out on our [GitHub](https://github.com/apify/crawlee-python) or join our [Discord community](https://discord.com/invite/jyEM2PRvMU). Happy scraping!
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
id: avoid-blocking
|
||||
title: Avoid getting blocked
|
||||
description: How to avoid getting blocked when scraping
|
||||
---
|
||||
|
||||
import ApiLink from '@site/src/components/ApiLink';
|
||||
import CodeBlock from '@theme/CodeBlock';
|
||||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock';
|
||||
|
||||
import PlaywrightDefaultFingerprintGenerator from '!!raw-loader!roa-loader!./code_examples/avoid_blocking/playwright_with_fingerprint_generator.py';
|
||||
import PlaywrightWithCamoufox from '!!raw-loader!roa-loader!../examples/code_examples/playwright_crawler_with_camoufox.py';
|
||||
import PlaywrightWithCloakBrowser from '!!raw-loader!roa-loader!./code_examples/avoid_blocking/playwright_with_cloakbrowser.py';
|
||||
|
||||
import PlaywrightDefaultFingerprintGeneratorWithArgs from '!!raw-loader!./code_examples/avoid_blocking/default_fingerprint_generator_with_args.py';
|
||||
|
||||
A scraper might get blocked for numerous reasons. Let's narrow it down to the two main ones. The first is a bad or blocked IP address. You can learn about this topic in the [proxy management guide](./proxy-management). The second reason is [browser fingerprints](https://pixelprivacy.com/resources/browser-fingerprinting/) (or signatures), which we will explore more in this guide. Check the [Apify Academy anti-scraping course](https://docs.apify.com/academy/anti-scraping) to gain a deeper theoretical understanding of blocking and learn a few tips and tricks.
|
||||
|
||||
Browser fingerprint is a collection of browser attributes and significant features that can show if our browser is a bot or a real user. Moreover, most browsers have these unique features that allow the website to track the browser even within different IP addresses. This is the main reason why scrapers should change browser fingerprints while doing browser-based scraping. In return, it should significantly reduce the blocking.
|
||||
|
||||
## Using browser fingerprints
|
||||
|
||||
Changing browser fingerprints can be a tedious job. Luckily, Crawlee provides this feature with minimal configuration necessary - the usage of fingerprints in <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> is enabled by default. You can customize the fingerprints by using the `fingerprint_generator` argument of the <ApiLink to="class/PlaywrightCrawler#__init__">`PlaywrightCrawler.__init__`</ApiLink>, either pass your own implementation of <ApiLink to="class/FingerprintGenerator">`FingerprintGenerator`</ApiLink> or use <ApiLink to="class/BrowserforgeFingerprintGenerator">`DefaultFingerprintGenerator`</ApiLink>.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightDefaultFingerprintGenerator}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
In certain cases we want to narrow down the fingerprints used - e.g. specify a certain operating system, locale or browser. This is also possible with Crawlee - the crawler can have the generation algorithm customized to reflect the particular browser version and many more. For description of fingerprint generation options please see <ApiLink to="class/HeaderGeneratorOptions">`HeaderGeneratorOptions`</ApiLink>, <ApiLink to="class/ScreenOptions">`ScreenOptions`</ApiLink> and <ApiLink to="class/BrowserforgeFingerprintGenerator#__init__">`DefaultFingerprintGenerator.__init__`</ApiLink> See the example below:
|
||||
|
||||
<CodeBlock className="language-python">
|
||||
{PlaywrightDefaultFingerprintGeneratorWithArgs}
|
||||
</CodeBlock>
|
||||
|
||||
If you do not want to use fingerprints, then pass `fingerprint_generator=None` argument to the <ApiLink to="class/PlaywrightCrawler#__init__">`PlaywrightCrawler.__init__`</ApiLink>.
|
||||
|
||||
## Using Camoufox
|
||||
|
||||
In some cases even <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> with fingerprints is not enough. You can try using <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> together with [Camoufox](https://camoufox.com/). See the example integration below:
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightWithCamoufox}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
## Using CloakBrowser
|
||||
|
||||
For sites with aggressive anti-bot protection, [CloakBrowser](https://github.com/CloakHQ/CloakBrowser) takes a different approach. Instead of overriding fingerprints at the JavaScript level (which anti-bot scripts can detect as tampering), CloakBrowser ships a custom Chromium binary with fingerprints modified directly in the C++ source code. It is also Chromium-based, which can matter when a target site behaves differently with Firefox than with Chrome. Install it separately with `pip install cloakbrowser` — the plugin calls `ensure_binary()` which automatically downloads and caches the Chromium binary on first run.
|
||||
|
||||
<RunnableCodeBlock className="language-python" language="python">
|
||||
{PlaywrightWithCloakBrowser}
|
||||
</RunnableCodeBlock>
|
||||
|
||||
**Related links**
|
||||
|
||||
- [Fingerprint Suite Docs](https://github.com/apify/fingerprint-suite)
|
||||
- [Apify Academy anti-scraping course](https://docs.apify.com/academy/anti-scraping)
|
||||
@@ -0,0 +1,20 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.fingerprint_suite import (
|
||||
DefaultFingerprintGenerator,
|
||||
HeaderGeneratorOptions,
|
||||
ScreenOptions,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
fingerprint_generator = DefaultFingerprintGenerator(
|
||||
header_options=HeaderGeneratorOptions(browsers=['chrome']),
|
||||
screen_options=ScreenOptions(min_width=400),
|
||||
)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,81 @@
|
||||
import asyncio
|
||||
|
||||
# CloakBrowser is an external package. Install it separately.
|
||||
from cloakbrowser.config import IGNORE_DEFAULT_ARGS, get_default_stealth_args
|
||||
from cloakbrowser.download import ensure_binary
|
||||
from typing_extensions import override
|
||||
|
||||
from crawlee.browsers import (
|
||||
BrowserPool,
|
||||
PlaywrightBrowserController,
|
||||
PlaywrightBrowserPlugin,
|
||||
)
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
class CloakBrowserPlugin(PlaywrightBrowserPlugin):
|
||||
"""Example browser plugin that uses CloakBrowser's patched Chromium,
|
||||
but otherwise keeps the functionality of PlaywrightBrowserPlugin.
|
||||
"""
|
||||
|
||||
@override
|
||||
async def new_browser(self) -> PlaywrightBrowserController:
|
||||
if not self._playwright:
|
||||
raise RuntimeError('Playwright browser plugin is not initialized.')
|
||||
|
||||
binary_path = ensure_binary()
|
||||
stealth_args = get_default_stealth_args()
|
||||
|
||||
# Merge CloakBrowser stealth args with any user-provided launch options.
|
||||
launch_options = dict(self._browser_launch_options)
|
||||
launch_options.pop('executable_path', None)
|
||||
launch_options.pop('chromium_sandbox', None)
|
||||
existing_args = list(launch_options.pop('args', []))
|
||||
launch_options['args'] = [*existing_args, *stealth_args]
|
||||
|
||||
return PlaywrightBrowserController(
|
||||
browser=await self._playwright.chromium.launch(
|
||||
executable_path=binary_path,
|
||||
ignore_default_args=IGNORE_DEFAULT_ARGS,
|
||||
**launch_options,
|
||||
),
|
||||
max_open_pages_per_browser=1,
|
||||
# CloakBrowser handles fingerprints at the binary level.
|
||||
header_generator=None,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
# Custom browser pool. Gives users full control over browsers used by the crawler.
|
||||
browser_pool=BrowserPool(plugins=[CloakBrowserPlugin()]),
|
||||
)
|
||||
|
||||
# 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 some data from the page using Playwright's API.
|
||||
posts = await context.page.query_selector_all('.athing')
|
||||
for post in posts:
|
||||
# Get the HTML elements for the title and rank within each post.
|
||||
title_element = await post.query_selector('.title a')
|
||||
|
||||
# Extract the data we want from the elements.
|
||||
title = await title_element.inner_text() if title_element else None
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data({'title': title})
|
||||
|
||||
# Find a link to the next page and enqueue it if it exists.
|
||||
await context.enqueue_links(selector='.morelink')
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://news.ycombinator.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,23 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Fingerprint generator is used by default.
|
||||
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} ...')
|
||||
|
||||
# Find a link to the next page and enqueue it if it exists.
|
||||
await context.enqueue_links(selector='.morelink')
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://news.ycombinator.com/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
import asyncio
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from warcio.statusandheaders import StatusAndHeaders
|
||||
from warcio.warcwriter import WARCWriter
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
|
||||
|
||||
async def archive_response(context: ParselCrawlingContext, writer: WARCWriter) -> None:
|
||||
"""Helper function for archiving response in WARC format."""
|
||||
# Create WARC records for response
|
||||
response_body = await context.http_response.read()
|
||||
response_payload_stream = io.BytesIO(response_body)
|
||||
|
||||
response_headers = StatusAndHeaders(
|
||||
str(context.http_response.status_code),
|
||||
context.http_response.headers,
|
||||
protocol='HTTP/1.1',
|
||||
)
|
||||
response_record = writer.create_warc_record(
|
||||
context.request.url,
|
||||
'response',
|
||||
payload=response_payload_stream,
|
||||
length=len(response_body),
|
||||
http_headers=response_headers,
|
||||
)
|
||||
writer.write_record(response_record)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = ParselCrawler(
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Create a WARC archive file a prepare the writer.
|
||||
archive = Path('example.warc.gz')
|
||||
with archive.open('wb') as output:
|
||||
writer = WARCWriter(output, gzip=True)
|
||||
|
||||
# Create a WARC info record to store metadata about the archive.
|
||||
warcinfo_payload = {
|
||||
'software': 'Crawlee',
|
||||
'format': 'WARC/1.1',
|
||||
'description': 'Example archive created with ParselCrawler',
|
||||
}
|
||||
writer.write_record(writer.create_warcinfo_record(archive.name, warcinfo_payload))
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Archiving {context.request.url} ...')
|
||||
await archive_response(context=context, writer=writer)
|
||||
await context.enqueue_links(strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,85 @@
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.async_api import Request
|
||||
from warcio.statusandheaders import StatusAndHeaders
|
||||
from warcio.warcwriter import WARCWriter
|
||||
|
||||
from crawlee.crawlers import (
|
||||
PlaywrightCrawler,
|
||||
PlaywrightCrawlingContext,
|
||||
PlaywrightPreNavCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def archive_response(
|
||||
request: Request, writer: WARCWriter, logger: logging.Logger
|
||||
) -> None:
|
||||
"""Helper function for archiving response in WARC format."""
|
||||
response = await request.response()
|
||||
if not response:
|
||||
logger.warning(f'Could not get response {request.url}')
|
||||
return
|
||||
try:
|
||||
response_body = await response.body()
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not get response body for {response.url}: {e}')
|
||||
return
|
||||
logger.info(f'Archiving resource {response.url}')
|
||||
response_payload_stream = io.BytesIO(response_body)
|
||||
response_headers = StatusAndHeaders(
|
||||
str(response.status), response.headers, protocol='HTTP/1.1'
|
||||
)
|
||||
response_record = writer.create_warc_record(
|
||||
response.url,
|
||||
'response',
|
||||
payload=response_payload_stream,
|
||||
length=len(response_body),
|
||||
http_headers=response_headers,
|
||||
)
|
||||
writer.write_record(response_record)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
max_requests_per_crawl=1,
|
||||
headless=False,
|
||||
)
|
||||
|
||||
# Create a WARC archive file a prepare the writer.
|
||||
archive = Path('example.warc.gz')
|
||||
with archive.open('wb') as output:
|
||||
writer = WARCWriter(output, gzip=True)
|
||||
|
||||
# Create a WARC info record to store metadata about the archive.
|
||||
warcinfo_payload = {
|
||||
'software': 'Crawlee',
|
||||
'format': 'WARC/1.1',
|
||||
'description': 'Example archive created with PlaywrightCrawler',
|
||||
}
|
||||
writer.write_record(writer.create_warcinfo_record(archive.name, warcinfo_payload))
|
||||
|
||||
@crawler.pre_navigation_hook
|
||||
async def archiving_hook(context: PlaywrightPreNavCrawlingContext) -> None:
|
||||
# Ensure that all responses with additional resources are archived
|
||||
context.page.on(
|
||||
'requestfinished',
|
||||
partial(archive_response, logger=context.log, writer=writer),
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
# For some sites, where the content loads dynamically,
|
||||
# it is needed to scroll the page to load all content.
|
||||
# It slows down the crawling, but ensures that all content is loaded.
|
||||
await context.infinite_scroll()
|
||||
await context.enqueue_links(strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,30 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
|
||||
from crawlee.proxy_configuration import ProxyConfiguration
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = PlaywrightCrawler(
|
||||
# Use the local wayback server as a proxy
|
||||
proxy_configuration=ProxyConfiguration(proxy_urls=['http://localhost:8080/']),
|
||||
# Ignore the HTTPS errors if you have not followed pywb CA setup instructions
|
||||
browser_launch_options={'ignore_https_errors': True},
|
||||
max_requests_per_crawl=10,
|
||||
headless=False,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: PlaywrightCrawlingContext) -> None:
|
||||
context.log.info(f'Archiving {context.request.url} ...')
|
||||
# For some sites, where the content loads dynamically,
|
||||
# it is needed to scroll the page to load all content.
|
||||
# It slows down the crawling, but ensures that all content is loaded.
|
||||
await context.infinite_scroll()
|
||||
await context.enqueue_links(strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from crawlee import HttpHeaders
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
from crawlee.errors import HttpStatusCodeError
|
||||
from crawlee.sessions import SessionPool
|
||||
|
||||
# Using a placeholder refresh token for this example
|
||||
REFRESH_TOKEN = 'PLACEHOLDER'
|
||||
UNAUTHORIZED_CODE = 401
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(
|
||||
max_request_retries=2,
|
||||
# Only treat 403 as a blocking status code, not 401
|
||||
session_pool=SessionPool(create_session_settings={'blocked_status_codes': [403]}),
|
||||
# Don't treat 401 responses as errors
|
||||
ignore_http_error_status_codes=[UNAUTHORIZED_CODE],
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
# Now we can handle 401 responses ourselves
|
||||
if context.http_response.status_code == UNAUTHORIZED_CODE:
|
||||
# Get a fresh access token
|
||||
headers = {'authorization': f'Bearer {REFRESH_TOKEN}'}
|
||||
response = await context.send_request(
|
||||
'https://placeholder.org/refresh', headers=headers
|
||||
)
|
||||
data = json.loads(await response.read())
|
||||
# Add the new token to our `Request` headers
|
||||
context.request.headers |= HttpHeaders(
|
||||
{'authorization': f'Bearer {data["access_token"]}'},
|
||||
)
|
||||
# Trigger a retry with our updated headers
|
||||
raise HttpStatusCodeError('Unauthorized', status_code=UNAUTHORIZED_CODE)
|
||||
|
||||
await crawler.run(['http://httpbingo.org/status/401'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,30 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BasicCrawlingContext, HttpCrawler, HttpCrawlingContext
|
||||
from crawlee.errors import HttpStatusCodeError, SessionError
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(max_request_retries=5)
|
||||
|
||||
# Create a parsing error for demonstration
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
raise ValueError('Simulated parsing error')
|
||||
|
||||
# This handler runs before any retry attempts
|
||||
@crawler.error_handler
|
||||
async def retry_handler(context: BasicCrawlingContext, error: Exception) -> None:
|
||||
context.log.error(f'Failed request {context.request.url}')
|
||||
# Only allow retries for network-related errors
|
||||
if not isinstance(error, (SessionError, HttpStatusCodeError)):
|
||||
context.log.error('Non-network error detected')
|
||||
# Stop further retry attempts for this `Request`
|
||||
context.request.no_retry = True
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,40 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import BasicCrawlingContext, HttpCrawler, HttpCrawlingContext
|
||||
from crawlee.errors import ProxyError
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Set how many session rotations will happen before calling the error handler
|
||||
# when ProxyError occurs
|
||||
crawler = HttpCrawler(max_session_rotations=5, max_request_retries=6)
|
||||
|
||||
# For this example, we'll create a proxy error in our handler
|
||||
@crawler.router.default_handler
|
||||
async def default_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
raise ProxyError('Simulated proxy error')
|
||||
|
||||
# This handler runs after all retry attempts are exhausted
|
||||
@crawler.failed_request_handler
|
||||
async def failed_handler(context: BasicCrawlingContext, error: Exception) -> None:
|
||||
context.log.error(f'Failed request {context.request.url}, after 5 rotations')
|
||||
request = context.request
|
||||
# For proxy errors, we can add a new `Request` to try again
|
||||
if isinstance(error, ProxyError) and not request.unique_key.startswith('retry'):
|
||||
context.log.info(f'Retrying {request.url} ...')
|
||||
# Create a new `Request` with a modified key to avoid deduplication
|
||||
new_request = Request.from_url(
|
||||
request.url, unique_key=f'retry{request.unique_key}'
|
||||
)
|
||||
|
||||
# Add the new `Request` to the `Queue`
|
||||
rq = await crawler.get_request_manager()
|
||||
await rq.add_request(new_request)
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
from crawlee.http_clients import CurlImpersonateHttpClient
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
http_client = CurlImpersonateHttpClient(
|
||||
# Optional additional keyword arguments for `curl_cffi.requests.AsyncSession`.
|
||||
timeout=10,
|
||||
impersonate='chrome131',
|
||||
)
|
||||
|
||||
crawler = ParselCrawler(
|
||||
http_client=http_client,
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all links from the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.selector.css('title::text').get(),
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
from crawlee.http_clients import HttpxHttpClient
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
http_client = HttpxHttpClient(
|
||||
# Optional additional keyword arguments for `httpx.AsyncClient`.
|
||||
timeout=10,
|
||||
follow_redirects=True,
|
||||
)
|
||||
|
||||
crawler = ParselCrawler(
|
||||
http_client=http_client,
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all links from the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.selector.css('title::text').get(),
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,43 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
from crawlee.http_clients import ImpitHttpClient
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
http_client = ImpitHttpClient(
|
||||
# Optional additional keyword arguments for `impit.AsyncClient`.
|
||||
http3=True,
|
||||
browser='firefox',
|
||||
verify=True,
|
||||
)
|
||||
|
||||
crawler = ParselCrawler(
|
||||
http_client=http_client,
|
||||
# Limit the crawl to max requests. Remove or increase it for crawling all links.
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler, which will be called for every request.
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Enqueue all links from the page.
|
||||
await context.enqueue_links()
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.selector.css('title::text').get(),
|
||||
}
|
||||
|
||||
# Push the extracted data to the default dataset.
|
||||
await context.push_data(data)
|
||||
|
||||
# Run the crawler with the initial list of URLs.
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create a BeautifulSoupCrawler instance
|
||||
crawler = BeautifulSoupCrawler(
|
||||
# Limit the crawl to 10 requests
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url}')
|
||||
|
||||
# Extract data using BeautifulSoup
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.soup.title.string if context.soup.title else None,
|
||||
}
|
||||
|
||||
# Push extracted data to the dataset
|
||||
await context.push_data(data)
|
||||
|
||||
# Enqueue links found on the page for further crawling
|
||||
await context.enqueue_links()
|
||||
|
||||
# Run the crawler
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create an HttpCrawler instance - no automatic parsing
|
||||
crawler = HttpCrawler(
|
||||
# Limit the crawl to 10 requests
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url}')
|
||||
|
||||
# Get the raw response content
|
||||
response_body = await context.http_response.read()
|
||||
response_text = response_body.decode('utf-8')
|
||||
|
||||
# Extract title manually using regex (since we don't have a parser)
|
||||
title_match = re.search(
|
||||
r'<title[^>]*>([^<]+)</title>', response_text, re.IGNORECASE
|
||||
)
|
||||
title = title_match.group(1).strip() if title_match else None
|
||||
|
||||
# Extract basic information
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': title,
|
||||
}
|
||||
|
||||
# Push extracted data to the dataset
|
||||
await context.push_data(data)
|
||||
|
||||
# Simple link extraction for further crawling
|
||||
href_pattern = r'href=["\']([^"\']+)["\']'
|
||||
matches = re.findall(href_pattern, response_text, re.IGNORECASE)
|
||||
|
||||
# Enqueue first few links found (limit to avoid too many requests)
|
||||
for href in matches[:3]:
|
||||
if href.startswith('http') and 'crawlee.dev' in href:
|
||||
await context.add_requests([href])
|
||||
|
||||
# Run the crawler
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,63 @@
|
||||
import asyncio
|
||||
|
||||
from pydantic import ValidationError
|
||||
from selectolax.lexbor import LexborHTMLParser
|
||||
from yarl import URL
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(
|
||||
max_request_retries=1,
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Parse the HTML content using Selectolax with Lexbor backend.
|
||||
parsed_html = LexborHTMLParser(await context.http_response.read())
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': parsed_html.css_first('title').text(),
|
||||
'h1s': [h1.text() for h1 in parsed_html.css('h1')],
|
||||
'h2s': [h2.text() for h2 in parsed_html.css('h2')],
|
||||
'h3s': [h3.text() for h3 in parsed_html.css('h3')],
|
||||
}
|
||||
await context.push_data(data)
|
||||
|
||||
# Css selector to extract valid href attributes.
|
||||
links_selector = (
|
||||
'a[href]:not([href^="#"]):not([href^="javascript:"]):not([href^="mailto:"])'
|
||||
)
|
||||
base_url = URL(context.request.url)
|
||||
extracted_requests = []
|
||||
|
||||
# Extract links.
|
||||
for item in parsed_html.css(links_selector):
|
||||
href = item.attributes.get('href')
|
||||
if not href:
|
||||
continue
|
||||
|
||||
# Convert relative URLs to absolute if needed.
|
||||
url = str(base_url.join(URL(href)))
|
||||
try:
|
||||
request = Request.from_url(url)
|
||||
except ValidationError as exc:
|
||||
context.log.warning(f'Skipping invalid URL "{url}": {exc}')
|
||||
continue
|
||||
extracted_requests.append(request)
|
||||
|
||||
# Add extracted requests to the queue with the same-domain strategy.
|
||||
await context.add_requests(extracted_requests, strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
import asyncio
|
||||
|
||||
from lxml import html
|
||||
from pydantic import ValidationError
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(
|
||||
max_request_retries=1,
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Parse the HTML content using lxml.
|
||||
parsed_html = html.fromstring(await context.http_response.read())
|
||||
|
||||
# Extract data from the page.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': parsed_html.findtext('.//title'),
|
||||
'h1s': [h1.text_content() for h1 in parsed_html.findall('.//h1')],
|
||||
'h2s': [h2.text_content() for h2 in parsed_html.findall('.//h2')],
|
||||
'h3s': [h3.text_content() for h3 in parsed_html.findall('.//h3')],
|
||||
}
|
||||
await context.push_data(data)
|
||||
|
||||
# Convert relative URLs to absolute before extracting links.
|
||||
parsed_html.make_links_absolute(context.request.url, resolve_base_href=True)
|
||||
|
||||
# Xpath 1.0 selector for extracting valid href attributes.
|
||||
links_xpath = (
|
||||
'//a/@href[not(starts-with(., "#")) '
|
||||
'and not(starts-with(., "javascript:")) '
|
||||
'and not(starts-with(., "mailto:"))]'
|
||||
)
|
||||
|
||||
extracted_requests = []
|
||||
|
||||
# Extract links.
|
||||
for url in parsed_html.xpath(links_xpath):
|
||||
try:
|
||||
request = Request.from_url(url)
|
||||
except ValidationError as exc:
|
||||
context.log.warning(f'Skipping invalid URL "{url}": {exc}')
|
||||
continue
|
||||
extracted_requests.append(request)
|
||||
|
||||
# Add extracted requests to the queue with the same-domain strategy.
|
||||
await context.add_requests(extracted_requests, strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,77 @@
|
||||
import asyncio
|
||||
|
||||
from lxml import html
|
||||
from pydantic import ValidationError
|
||||
from saxonche import PySaxonProcessor
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(
|
||||
max_request_retries=1,
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Create Saxon processor once and reuse across requests.
|
||||
saxon_proc = PySaxonProcessor(license=False)
|
||||
xpath_proc = saxon_proc.new_xpath_processor()
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Parse HTML with lxml.
|
||||
parsed_html = html.fromstring(await context.http_response.read())
|
||||
# Convert relative URLs to absolute before extracting links.
|
||||
parsed_html.make_links_absolute(context.request.url, resolve_base_href=True)
|
||||
# Convert parsed HTML to XML for Saxon processing.
|
||||
xml = html.tostring(parsed_html, encoding='unicode', method='xml')
|
||||
# Parse XML with Saxon.
|
||||
parsed_xml = saxon_proc.parse_xml(xml_text=xml)
|
||||
# Set the parsed context for XPath evaluation.
|
||||
xpath_proc.set_context(xdm_item=parsed_xml)
|
||||
|
||||
# Extract data using XPath 2.0 string() function.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': xpath_proc.evaluate_single('.//title/string()'),
|
||||
'h1s': [str(h) for h in (xpath_proc.evaluate('//h1/string()') or [])],
|
||||
'h2s': [str(h) for h in (xpath_proc.evaluate('//h2/string()') or [])],
|
||||
'h3s': [str(h) for h in (xpath_proc.evaluate('//h3/string()') or [])],
|
||||
}
|
||||
await context.push_data(data)
|
||||
|
||||
# XPath 2.0 with distinct-values() to get unique links and remove fragments.
|
||||
links_xpath = """
|
||||
distinct-values(
|
||||
for $href in //a/@href[
|
||||
not(starts-with(., "#"))
|
||||
and not(starts-with(., "javascript:"))
|
||||
and not(starts-with(., "mailto:"))
|
||||
]
|
||||
return replace($href, "#.*$", "")
|
||||
)
|
||||
"""
|
||||
|
||||
extracted_requests = []
|
||||
|
||||
# Extract links.
|
||||
for item in xpath_proc.evaluate(links_xpath) or []:
|
||||
url = item.string_value
|
||||
try:
|
||||
request = Request.from_url(url)
|
||||
except ValidationError as exc:
|
||||
context.log.warning(f'Skipping invalid URL "{url}": {exc}')
|
||||
continue
|
||||
extracted_requests.append(request)
|
||||
|
||||
# Add extracted requests to the queue with the same-domain strategy.
|
||||
await context.add_requests(extracted_requests, strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create a ParselCrawler instance
|
||||
crawler = ParselCrawler(
|
||||
# Limit the crawl to 10 requests
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
# Define the default request handler
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: ParselCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url}')
|
||||
|
||||
# Extract data using Parsel's XPath and CSS selectors
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': context.selector.xpath('//title/text()').get(),
|
||||
}
|
||||
|
||||
# Push extracted data to the dataset
|
||||
await context.push_data(data)
|
||||
|
||||
# Enqueue links found on the page for further crawling
|
||||
await context.enqueue_links()
|
||||
|
||||
# Run the crawler
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
import asyncio
|
||||
|
||||
from pydantic import ValidationError
|
||||
from pyquery import PyQuery
|
||||
from yarl import URL
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = HttpCrawler(
|
||||
max_request_retries=1,
|
||||
max_requests_per_crawl=10,
|
||||
)
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: HttpCrawlingContext) -> None:
|
||||
context.log.info(f'Processing {context.request.url} ...')
|
||||
|
||||
# Parse the HTML content using PyQuery.
|
||||
parsed_html = PyQuery(await context.http_response.read())
|
||||
|
||||
# Extract data using jQuery-style selectors.
|
||||
data = {
|
||||
'url': context.request.url,
|
||||
'title': parsed_html('title').text(),
|
||||
'h1s': [h1.text() for h1 in parsed_html('h1').items()],
|
||||
'h2s': [h2.text() for h2 in parsed_html('h2').items()],
|
||||
'h3s': [h3.text() for h3 in parsed_html('h3').items()],
|
||||
}
|
||||
await context.push_data(data)
|
||||
|
||||
# Css selector to extract valid href attributes.
|
||||
links_selector = (
|
||||
'a[href]:not([href^="#"]):not([href^="javascript:"]):not([href^="mailto:"])'
|
||||
)
|
||||
base_url = URL(context.request.url)
|
||||
|
||||
extracted_requests = []
|
||||
|
||||
# Extract links.
|
||||
for item in parsed_html(links_selector).items():
|
||||
href = item.attr('href')
|
||||
if not href:
|
||||
continue
|
||||
|
||||
# Convert relative URLs to absolute if needed.
|
||||
url = str(base_url.join(URL(str(href))))
|
||||
try:
|
||||
request = Request.from_url(url)
|
||||
except ValidationError as exc:
|
||||
context.log.warning(f'Skipping invalid URL "{url}": {exc}')
|
||||
continue
|
||||
extracted_requests.append(request)
|
||||
|
||||
# Add extracted requests to the queue with the same-domain strategy.
|
||||
await context.add_requests(extracted_requests, strategy='same-domain')
|
||||
|
||||
await crawler.run(['https://crawlee.dev'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user