Python Playwright scraper
A real-browser scraper that gets data HTTP scrapers miss. Good for social feeds, dashboards, or single-page apps.
my_actor/main.py
my_actor/__main__.py
1"""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/python7"""8
9from __future__ import annotations10
11from urllib.parse import urljoin12
13from apify import Actor, Request14from playwright.async_api import async_playwright15
16# Note: To run this Actor locally, ensure that Playwright browsers are installed.17# Run `playwright install --with-deps` in the Actor's virtual environment to install them.18# When running on the Apify platform, these dependencies are already included19# in the Actor's Docker image.20
21# Limit the crawl to max requests. Increase it to crawl more links.22MAX_REQUESTS_PER_CRAWL = 1023
24
25async def main() -> None:26 """Define a main entry point for the Apify Actor.27
28 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.29 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in30 the field of web scraping significantly.31 """32 # Enter the context of the Actor.33 async with Actor:34 # Retrieve the Actor input, and use default values if not provided.35 actor_input = await Actor.get_input() or {}36 start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])37 max_depth = actor_input.get('max_depth', 1)38
39 # Exit if no start URLs are provided.40 if not start_urls:41 Actor.log.info('No start URLs specified in Actor input, exiting...')42 await Actor.exit()43
44 # Open the default request queue for handling URLs to be processed.45 request_queue = await Actor.open_request_queue()46
47 # Enqueue the start URLs with an initial crawl depth of 0.48 for start_url in start_urls:49 url = start_url.get('url')50 Actor.log.info(f'Enqueuing {url} ...')51 new_request = Request.from_url(url, user_data={'depth': 0})52 await request_queue.add_request(new_request)53
54 Actor.log.info('Launching Playwright...')55
56 # Launch Playwright and open a new browser context.57 async with async_playwright() as playwright:58 # Configure the browser to launch in headless mode as per Actor configuration.59 browser = await playwright.chromium.launch(60 headless=Actor.configuration.headless,61 args=['--disable-gpu'],62 )63 context = await browser.new_context()64
65 handled_requests = 066
67 # Process the URLs from the request queue.68 while handled_requests < MAX_REQUESTS_PER_CRAWL and (request := await request_queue.fetch_next_request()):69 url = request.url70
71 if not isinstance(request.user_data['depth'], (str, int)):72 raise TypeError('Request.depth is an unexpected type.')73
74 depth = int(request.user_data['depth'])75 Actor.log.info(f'Scraping {url} (depth={depth}) ...')76
77 try:78 # Open a new page in the browser context and navigate to the URL.79 page = await context.new_page()80 await page.goto(url)81
82 # If the current depth is less than max_depth, find nested links83 # and enqueue them.84 if depth < max_depth:85 for link in await page.locator('a').all():86 link_href = await link.get_attribute('href')87 link_url = urljoin(url, link_href)88
89 if link_url.startswith(('http://', 'https://')):90 Actor.log.info(f'Enqueuing {link_url} ...')91 new_request = Request.from_url(92 link_url,93 user_data={'depth': depth + 1},94 )95 await request_queue.add_request(new_request)96
97 # Extract the desired data.98 data = {99 'url': url,100 'title': await page.title(),101 }102
103 # Store the extracted data to the default dataset.104 await Actor.push_data(data)105
106 except Exception:107 Actor.log.exception(f'Cannot extract data from {url}.')108
109 finally:110 await page.close()111 # Mark the request as handled to ensure it is not processed again.112 await request_queue.mark_request_as_handled(request)113 handled_requests += 1- 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
- Playwright for web scraping in 2023
- Scraping single-page applications with Playwright
- How to scale Puppeteer and Playwright
- Integration with Zapier , Make, GitHub, Google Drive and other apps
- Video guide on getting data using Apify API
- A short guide on how to build web scrapers using code templates:
BeautifulSoup crawler
Get data from every page on a site. Good for simple sites like blogs, news, or product listings, but it can't run client-side JavaScript. Uses BeautifulSoup, Python's most popular HTML parser.
Empty Python Actor
An Actor with the Apify SDK set up, so you can build any tool you need.
Python one-page scraper
Get data from one web page with BeautifulSoup. The simplest way to start scraping.
Python project managed by uv
A general-purpose Python Actor with its project and dependencies managed by the uv package manager. A minimal starting point for any use case.
Python multi-page scraper
Get data from multiple web pages with BeautifulSoup. Fast and light for simple sites.
Python Selenium scraper
A Chrome browser scraper that renders JavaScript before extracting data. Good for social feeds, dashboards, or single-page apps.