Back to template gallery

Playwright + Chrome

Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.

Language

python

Tools

playwright

Use cases

Web scraping

src/main.py

src/__main__.py

1"""This module defines the main entry point for the Apify Actor.
2
3Feel free to modify this file to suit your specific needs.
4
5To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
6https://docs.apify.com/sdk/python
7"""
8
9from urllib.parse import urljoin
10
11from playwright.async_api import async_playwright
12
13from apify import Actor, Request
14
15# Note: To run this Actor locally, ensure that Playwright browsers are installed.
16# Run `playwright install --with-deps` in the Actor's virtual environment to install them.
17# When running on the Apify platform, these dependencies are already included in the Actor's Docker image.
18
19
20async def main() -> None:
21    """Main entry point for the Apify Actor.
22
23    This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.
24    Asynchronous execution is required for communication with Apify platform, and it also enhances performance in
25    the field of web scraping significantly.
26    """
27    async with Actor:
28        # Retrieve the Actor input, and use default values if not provided.
29        actor_input = await Actor.get_input() or {}
30        start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])
31        max_depth = actor_input.get('max_depth', 1)
32
33        # Exit if no start URLs are provided.
34        if not start_urls:
35            Actor.log.info('No start URLs specified in actor input, exiting...')
36            await Actor.exit()
37
38        # Open the default request queue for handling URLs to be processed.
39        request_queue = await Actor.open_request_queue()
40
41        # Enqueue the start URLs with an initial crawl depth of 0.
42        for start_url in start_urls:
43            url = start_url.get('url')
44            Actor.log.info(f'Enqueuing {url} ...')
45            request = Request.from_url(url, user_data={'depth': 0})
46            await request_queue.add_request(request)
47
48        Actor.log.info('Launching Playwright...')
49
50        # Launch Playwright and open a new browser context.
51        async with async_playwright() as playwright:
52            # Configure the browser to launch in headless mode as per Actor configuration.
53            browser = await playwright.chromium.launch(headless=Actor.config.headless)
54            context = await browser.new_context()
55
56            # Process the URLs from the request queue.
57            while request := await request_queue.fetch_next_request():
58                url = request.url
59                depth = request.user_data['depth']
60                Actor.log.info(f'Scraping {url} ...')
61
62                try:
63                    # Open a new page in the browser context and navigate to the URL.
64                    page = await context.new_page()
65                    await page.goto(url)
66
67                    # If the current depth is less than max_depth, find nested links and enqueue them.
68                    if depth < max_depth:
69                        for link in await page.locator('a').all():
70                            link_href = await link.get_attribute('href')
71                            link_url = urljoin(url, link_href)
72
73                            if link_url.startswith(('http://', 'https://')):
74                                Actor.log.info(f'Enqueuing {link_url} ...')
75                                request = Request.from_url(link_url, user_data={'depth': depth + 1})
76                                await request_queue.add_request(request)
77
78                    # Extract the desired data.
79                    data = {
80                        'url': url,
81                        'title': await page.title(),
82                    }
83
84                    # Store the extracted data to the default dataset.
85                    await Actor.push_data(data)
86
87                except Exception:
88                    Actor.log.exception(f'Cannot extract data from {url}.')
89
90                finally:
91                    await page.close()
92                    # Mark the request as handled to ensure it is not processed again.
93                    await request_queue.mark_request_as_handled(request)

Python Playwright template

Included features

  • Apify SDK for Python - a toolkit for building Apify Actors and scrapers in Python
  • Input schema - define and easily validate a schema for your Actor's input
  • Request queue - queues into which you can put the URLs you want to scrape
  • Dataset - store structured data where each object stored has the same attributes
  • Playwright - a browser automation library

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.