Language
π Image
python
Tools
π Image
crawlee
π Image
beautifulsoup
Use cases
Starter
Web scraping
Features
my_actor/main.py
my_actor/routes.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 annotations1011import asyncio1213from apify import Actor, Event14from crawlee.crawlers import BeautifulSoupCrawler1516from.routes import router171819asyncdefmain()->None:20"""Define a main entry point for the Apify Actor.2122 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.23 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in24 the field of web scraping significantly.25 """26# Enter the context of the Actor.27asyncwith Actor:28# Handle graceful abort - Actor is being stopped by user or platform29asyncdefon_aborting()->None:30# Persist any state, do any cleanup you need, and terminate the Actor using31# `await Actor.exit()` explicitly as soon as possible. This will help ensure that32# the Actor is doing best effort to honor any potential limits on costs of a33# single run set by the user.34# Wait 1 second to allow Crawlee/SDK state persistence operations to complete35# This is a temporary workaround until SDK implements proper state persistence in the aborting event36await asyncio.sleep(1)37await Actor.exit()3839 Actor.on(Event.ABORTING, on_aborting)4041# Retrieve the Actor input, and use default values if not provided.42 actor_input =await Actor.get_input()or{}43 start_urls =[44 url.get('url')45for url in actor_input.get(46'start_urls',47[{'url':'https://apify.com'}],48)49]5051# Exit if no start URLs are provided.52ifnot start_urls:53 Actor.log.info('No start URLs specified in Actor input, exiting...')54await Actor.exit()5556# Create a crawler.57 crawler = BeautifulSoupCrawler(58# Limit the crawl to max requests. Remove or increase it for crawling all links.59 max_requests_per_crawl=10,60# Set the request handler to the request router defined in routes.py.61 request_handler=router,62)6364# Run the crawler with the starting requests.65await crawler.run(start_urls)Python Crawlee & BeautifulSoup Actor Template
This template example was built with Crawlee for Python to scrape data from a website using Beautiful Soup wrapped into BeautifulSoupCrawler .
Quick Start
Once you've installed the dependencies, start the Actor:
$apify run
Once your Actor is ready, you can push it to the Apify Console:
apify login # first, you need to log in if you haven't already done soapify push
Project Structure
.actor/βββ actor.json # Actor config: name, version, env vars, runtime settingsβββ dataset_schema.json # Structure and representation of data produced by an Actorβββ input_schema.json # Input validation & Console form definitionβββ output_schema.json # Specifies where an Actor stores its outputsrc/βββ main.py # Actor entry point and orchestratorstorage/ # Local storage (mirrors Cloud during development)βββ datasets/ # Output items (JSON objects)βββ key_value_stores/ # Files, config, INPUTβββ request_queues/ # Pending crawl requestsDockerfile # Container image definition
For more information, see the Actor definition documentation.
How it works
This code is a Python script that uses BeautifulSoup to scrape data from a website. It then stores the website titles in a dataset.
- The crawler starts with URLs provided from the input
startUrlsfield defined by the input schema. Number of scraped pages is limited bymaxPagesPerCrawlfield from the input schema. - The crawler uses
requestHandlerfor each URL to extract the data from the page with the BeautifulSoup library and to save the title and URL of each page to the dataset. It also logs out each result that is being saved.
What's included
- Apify SDK - toolkit for building Actors
- Crawlee for Python - web scraping and browser automation library
- Input schema - define and easily validate a schema for your Actor's input
- Dataset - store structured data where each object stored has the same attributes
- Beautiful Soup - a library for pulling data out of HTML and XML files
- Proxy configuration - rotate IP addresses to prevent blocking
Resources
- Quick Start guide for building your first Actor
- Video introduction to Python SDK
- Webinar introducing to Crawlee for Python
- Apify Python SDK documentation
- Crawlee for Python documentation
- Python tutorials in Academy
- Integration with Zapier , Make, Google Drive and others
- Video guide on getting data using Apify API
Creating Actors with templates
Related templates
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.
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.
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.
