Apify SDK for Python
repository·master·Indexed 41 days ago
https://github.com/apify/apify-sdk-pythonThe official toolkit for building Apify Actors in Python (v4.0.2). It provides abstractions for managing the Actor lifecycle, interacting with cloud storage (datasets, key-value stores, request queues), and integrating with platform features like Apify Proxy and pay-per-event charging. Requires Python 3.11 or higher.
What's inside Apify
- The Apify SDK for Python is the official library for creating Apify Actors. It provides tools to manage the Actor lifecycle, access storage (datasets, key-value stores, request queues), handle platform events, and manage Apify Proxy. Actors can run locally or on the Apify platform, where they can be scaled, scheduled, and monetized.
Access Apify SDK for Python documentation
masterThe complete documentation for the Apify SDK for Python is hosted at docs.apify.com/sdk/python.
Key documentation sections include:
- Overview: Explains the SDK, Actors, and core components.
- Quick start: Instructions for creating, running, and deploying your first Python Actor.
- Concepts: Detailed information on Actor lifecycle, input, storages, events, proxy management, interacting with other Actors, webhooks, accessing the Apify API, logging, configuration, and pay-per-event.
- Guides: Integration guides for BeautifulSoup, Parsel, Playwright, Selenium, Crawlee, Scrapy, Scrapling, Crawl4AI, and Browser Use. Also covers using
uv, Pydantic for input validation, running web servers, building MCP servers, and hosting AI agents. - Upgrading: Migration guides for moving between major versions.
- API reference: Full technical reference for every class and method.
Build browser automation Actors with Playwright
masterPlaywright allows you to control web browsers (Chromium, Firefox, WebKit) programmatically to scrape dynamic websites that require JavaScript execution.
Key features for scraping include:
- Auto-waiting: Automatically waits for elements to be ready.
- Powerful selectors: Supports CSS, XPath, and a resilient locator API.
- Network interception: Allows blocking resources or mocking API responses.
- Headless/Headful modes: Supports both containerized environments and local debugging.
On the Apify platform, Playwright and the necessary browsers are preinstalled in the Docker images. For new projects, it is recommended to start from the Playwright & Python Actor template.
Explore related Apify projects
masterThe Apify ecosystem includes several complementary tools:
- Apify API client for Python: Used to talk to the Apify API directly (bundled with this SDK).
- Crawlee for Python: A web scraping and browser automation framework that is fully compatible with this SDK.
- Apify CLI: A command-line tool for creating, running, and deploying Actors locally and on the Apify platform.
- JavaScript/TypeScript equivalents: There are also versions of the Apify SDK, API client, and Crawlee available for Node.js.
Configure shared request queue access
masterThe
ApifyStorageClientoffers two modes for accessing request queues via therequest_queue_accessargument:'single'(default): Optimized for a single consumer. It is faster and cheaper but does not support concurrent consumption by multiple clients.'shared': Supports multiple consumers working on the same queue simultaneously. Use this when splitting a large crawl across parallel Actor runs or using a producer-worker pattern.
To use the shared mode, you must set it as the cloud client of the
SmartApifyStorageClientin the service locator before entering the Actor context.# Example of setting up a shared request queue # (Requires importing the appropriate client from crawlee) from apify import Actor from apify.storage_clients import SmartApifyStorageClient from crawlee.storage_clients import ApifyStorageClient # In the service locator setup (before Actor.init or Actor context) # This is a conceptual representation of the pattern described # where ApifyStorageClient is configured with request_queue_access='shared'Handle Actor migrations and graceful stops in Scrapy
masterWhen the Apify platform migrates an Actor or performs a graceful abort, the
ApifyGracefulStopExtensionandApifySchedulerwork together to prevent data loss and duplication:- Detection: The integration reacts to
MIGRATINGorABORTINGevents. - Scheduler Behavior: The
ApifySchedulerstops handing out new requests to Scrapy. - Cleanup: It waits for in-flight requests (including callbacks and item pipelines) to finish, then marks them as handled in the Apify Request Queue.
- Resumption: On the next run, the scheduler resumes from the pending requests in the queue. Only requests that were not finished during the abort are re-downloaded.
Note on Start URLs: By default,
Spider.start()yields URLs withdont_filter=True, which the integration maps toalways_enqueue=True. This causes restarted runs to crawl start URLs again. To ensure start URLs are deduplicated against the request queue, overridestart()and yield plain requests instead.- Detection: The integration reacts to
Redirect logs from Actor.call
masterWhen starting another Actor using
Actor.call, you can control how its logs appear in your current Actor's logs using theloggerargument:- Default (
logger=default): Logs from the called Actor are automatically redirected to the parent Actor's logs with default formatting. Entries include cyan-colored text identifying the called Actor's name and run ID. - Disable Redirection (
logger=None): No logs from the called Actor will be redirected to the parent. - Custom Logger: Pass your own
Loggerinstance to define custom formatters, filters, or handlers for the redirected logs.
from apify import Actor # 1. Default redirection Actor.call('other-actor-name') # 2. No redirection Actor.call('other-actor-name', logger=None) # 3. Custom logger redirection import logging custom_logger = logging.getLogger('custom') Actor.call('other-actor-name', logger=custom_logger)- Default (
Reboot an Actor on the Apify platform
masterRebooting instructs the Apify platform worker to restart your Actor from the beginning. This is useful for recovering from transient issues like blocked proxies or stuck browser environments.
Warning: All in-memory data is lost during a reboot. You must persist any essential state to external storage (like the Key-Value Store or Dataset) before triggering a reboot.
Choose the right Crawlee crawler for your task
masterCrawlee provides different crawler types depending on whether you need to handle static HTML or dynamic JavaScript-rendered content:
BeautifulSoupCrawler: Best for extracting data from static HTML pages. It is lightweight and efficient because it does not execute JavaScript. It usesBeautifulSoupfor parsing andImpitHttpClientfor HTTP communication.ParselCrawler: Similar toBeautifulSoupCrawlerbut uses theParsellibrary. It is generally faster and allows for more powerful data extraction using XPath selectors.PlaywrightCrawler: Designed for dynamic web pages that require JavaScript execution. It uses thePlaywrightlibrary to provide a full browser automation environment.
Choose a Scrapling fetcher
masterScrapling provides different fetchers depending on the target website's complexity. All are importable from
scrapling.fetchers.Fetcher/AsyncFetcher: Fast, lightweight HTTP requests. Best for static pages and APIs. Supports browser TLS-fingerprint impersonation (impersonate) and realistic headers (stealthy_headers).DynamicFetcher/DynamicSession: Full browser automation based on Playwright. Use.fetch()or.async_fetch()for JavaScript-heavy pages.StealthyFetcher/StealthySession: A hardened browser fetcher that can automatically solve Cloudflare Turnstile challenges by settingsolve_cloudflare=True.
Connect an agent to an LLM
masterThere are two primary methods for providing an LLM to your agent:
1. Apify OpenRouter Proxy (Recommended)
Use the OpenAI-compatible endpoint at
https://openrouter.apify.actor/api/v1. This allows you to access the full OpenRouter model catalog without managing individual provider API keys.- Authentication: The proxy uses the
APIFY_TOKENautomatically injected into the Actor run. - Billing: Token usage is billed against your Apify account.
- Model Selection: Change the
modelinput to any OpenRouter model slug (e.g.,openai/gpt-5.4-mini).
2. Direct Provider Integration
Call providers like OpenAI directly using your own API key.
- Security: Do not hardcode keys. Read them from environment variables.
- Setup: On Apify, set these as secret environment variables. Locally, export them in your shell.
- Authentication: The proxy uses the
Understand changes to default storage IDs in Configuration
masterIn v3.0, the default storage IDs in
Configurationhave changed from'default'toNone:Configuration.default_key_value_store_idis nowNoneConfiguration.default_dataset_idis nowNoneConfiguration.default_request_queue_idis nowNone
Impact: Previously, omitting an ID defaulted to a storage named
'default'. Now, it uses a newly created unnamed storage with an ID assigned by the Apify platform. Consecutive calls to get the default storage will return the same storage.