Language
π Image
python
Tools
π Image
playwright
π Image
chrome
Use cases
Web scraping
Automation
Features
my_actor/main.py
my_actor/__main__.py
1"""Module defines the main entry point for the Apify Actor.23Feel free to modify this file to suit your specific needs.45To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:6https://docs.apify.com/sdk/python7"""89from __future__ import annotations1011from urllib.parse import urljoin1213from apify import Actor, Request14from playwright.async_api import async_playwright1516# 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.202122asyncdefmain()->None:23"""Define a main entry point for the Apify Actor.2425 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.26 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in27 the field of web scraping significantly.28 """29# Enter the context of the Actor.30asyncwith Actor:31# Retrieve the Actor input, and use default values if not provided.32 actor_input =await Actor.get_input()or{}33 start_urls = actor_input.get('start_urls',[{'url':'https://apify.com'}])34 max_depth = actor_input.get('max_depth',1)3536# Exit if no start URLs are provided.37ifnot start_urls:38 Actor.log.info('No start URLs specified in Actor input, exiting...')39await Actor.exit()4041# Open the default request queue for handling URLs to be processed.42 request_queue =await Actor.open_request_queue()4344# Enqueue the start URLs with an initial crawl depth of 0.45for start_url in start_urls:46 url = start_url.get('url')47 Actor.log.info(f'Enqueuing {url} ...')48 new_request = Request.from_url(url, user_data={'depth':0})49await request_queue.add_request(new_request)5051 Actor.log.info('Launching Playwright...')5253# Launch Playwright and open a new browser context.54asyncwith async_playwright()as playwright:55# Configure the browser to launch in headless mode as per Actor configuration.56 browser =await playwright.chromium.launch(57 headless=Actor.configuration.headless,58 args=['--disable-gpu'],59)60 context =await browser.new_context()6162# Process the URLs from the request queue.63while request :=await request_queue.fetch_next_request():64 url = request.url6566ifnotisinstance(request.user_data['depth'],(str,int)):67raise TypeError('Request.depth is an unexpected type.')6869 depth =int(request.user_data['depth'])70 Actor.log.info(f'Scraping {url} (depth={depth}) ...')7172try:73# Open a new page in the browser context and navigate to the URL.74 page =await context.new_page()75await page.goto(url)7677# If the current depth is less than max_depth, find nested links78# and enqueue them.79if depth < max_depth:80for link inawait page.locator('a').all():81 link_href =await link.get_attribute('href')82 link_url = urljoin(url, link_href)8384if link_url.startswith(('http://','https://')):85 Actor.log.info(f'Enqueuing {link_url} ...')86 new_request = Request.from_url(87 link_url,88 user_data={'depth': depth +1},89)90await request_queue.add_request(new_request)9192# Extract the desired data.93 data ={94'url': url,95'title':await page.title(),96}9798# Store the extracted data to the default dataset.99await Actor.push_data(data)100101except Exception:102 Actor.log.exception(f'Cannot extract data from {url}.')103104finally:105await page.close()106# Mark the request as handled to ensure it is not processed again.107await 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
- 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:
Related templates
Crawlee + BeautifulSoup
Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a URL and store results to your Apify dataset.
Empty Python project
Start with Apify SDK already set up, then build any features you need.
OneβPage HTML Scraper with BeautifulSoup
Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.
BeautifulSoup
Example of a web scraper that uses Python HTTPX to scrape HTML from URLs provided on input, parses it using BeautifulSoup and saves results to storage.
Selenium + Chrome
Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.
Standby Python project
Start with a working Actor in Standby mode that stays ready in the background, then build any features you need.
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.
