Back to template gallery

Crawlee + Playwright + Camoufox

Crawl and scrape websites using Crawlee and Playwright with Camoufox. Start from a given start URLs, and store results to Apify dataset.

Language

python

Tools

crawlee

playwright

Use cases

Starter

Web scraping

Features

src/main.py

src/__main__.py

1from apify import Actor
2from camoufox import AsyncNewBrowser
3from crawlee.browsers import BrowserPool, PlaywrightBrowserController, PlaywrightBrowserPlugin
4from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
5from typing_extensions import override
6
7
8class CamoufoxPlugin(PlaywrightBrowserPlugin):
9 """Browser plugin that uses Camoufox Browser, but otherwise keeps the functionality of PlaywrightBrowserPlugin."""
10
11 @override
12 async def new_browser(self) -> PlaywrightBrowserController:
13 if not self._playwright:
14 raise RuntimeError('Playwright browser plugin is not initialized.')
15
16 return PlaywrightBrowserController(
17 browser=await AsyncNewBrowser(self._playwright, headless=True),
18 max_open_pages_per_browser=1, # Increase, if camoufox can handle it in your use case.
19 header_generator=None, # This turns off the crawlee header_generation. Camoufox has its own.
20 )
21
22
23async def main() -> None:
24 """Define a main entry point for the Apify Actor.
25
26 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.
27 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in
28 the field of web scraping significantly.
29 """
30 # Enter the context of the Actor.
31 async with Actor:
32 # Retrieve the Actor input, and use default values if not provided.
33 actor_input = await Actor.get_input() or {}
34 start_urls = [
35 url.get('url')
36 for url in actor_input.get(
37 'start_urls',
38 [{'url': 'https://apify.com'}],
39 )
40 ]
41
42 # Exit if no start URLs are provided.
43 if not start_urls:
44 Actor.log.info('No start URLs specified in Actor input, exiting...')
45 await Actor.exit()
46
47 # Create a crawler.
48 crawler = PlaywrightCrawler(
49 # Limit the crawl to max requests. Remove or increase it for crawling all links.
50 max_requests_per_crawl=10,
51 browser_pool=BrowserPool(plugins=[CamoufoxPlugin()]),
52 )
53
54 # Define a request handler, which will be called for every request.
55 @crawler.router.default_handler
56 async def request_handler(context: PlaywrightCrawlingContext) -> None:
57 url = context.request.url
58 Actor.log.info(f'Scraping {url}...')
59
60 # Extract the desired data.
61 data = {
62 'url': context.request.url,
63 'title': await context.page.title(),
64 'h1s': [await h1.text_content() for h1 in await context.page.locator('h1').all()],
65 'h2s': [await h2.text_content() for h2 in await context.page.locator('h2').all()],
66 'h3s': [await h3.text_content() for h3 in await context.page.locator('h3').all()],
67 }
68
69 # Store the extracted data to the default dataset.
70 await context.push_data(data)
71
72 # Enqueue additional links found on the current page.
73 await context.enqueue_links()
74
75 # Run the crawler with the starting requests.
76 await crawler.run(start_urls)

Python Crawlee with Playwright template with Camoufox

A template for web scraping data from websites starting from provided URLs using Python. The starting URLs are passed through the Actor's input schema, defined by the input schema. The template uses Crawlee for Python for efficient web crawling, making requests via headless browser managed by Playwright, and handling each request through a user-defined handler that uses Playwright API to extract data from the page. Enqueued URLs are managed in the request queue, and the extracted data is saved in a dataset for easy access. It uses Camoufox - a stealthy fork of Firefox - preinstalled. Note that Camoufox might consume more resources than the default Playwright-bundled Chromium or Firefox.

Included features

  • Apify SDK - a toolkit for building Apify Actors in Python.
  • Crawlee for Python - a web scraping and browser automation library.
  • Input schema - define and validate a schema for your Actor's input.
  • Request queue - manage the URLs you want to scrape in a queue.
  • Dataset - store and access structured data extracted from web pages.
  • Playwright - a library for managing headless browsers.
  • Camoufox - a stealthy fork of Firefox.

Resources

Already have a solution in mind?

Sign up for a free Apify account and deploy your code to the platform in just a few minutes! If you want a head start without coding it yourself, browse our Store of existing solutions.