Apify SDK for Python

repository·master·Indexed 41 days ago

https://github.com/apify/apify-sdk-python

The 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.

Tokens
46.4K
Snippets
138
Records
214
Agent score
49%

What's inside Apify

  1. Access Apify SDK for Python documentation

    master

    The 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.
  2. Build browser automation Actors with Playwright

    master

    Playwright 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.

  3. Explore related Apify projects

    master

    The 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.
  4. Configure shared request queue access

    master

    The ApifyStorageClient offers two modes for accessing request queues via the request_queue_access argument:

    • '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 SmartApifyStorageClient in 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'
  5. Handle Actor migrations and graceful stops in Scrapy

    master

    When the Apify platform migrates an Actor or performs a graceful abort, the ApifyGracefulStopExtension and ApifyScheduler work together to prevent data loss and duplication:

    1. Detection: The integration reacts to MIGRATING or ABORTING events.
    2. Scheduler Behavior: The ApifyScheduler stops handing out new requests to Scrapy.
    3. Cleanup: It waits for in-flight requests (including callbacks and item pipelines) to finish, then marks them as handled in the Apify Request Queue.
    4. 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 with dont_filter=True, which the integration maps to always_enqueue=True. This causes restarted runs to crawl start URLs again. To ensure start URLs are deduplicated against the request queue, override start() and yield plain requests instead.

  6. Redirect logs from Actor.call

    master

    When starting another Actor using Actor.call, you can control how its logs appear in your current Actor's logs using the logger argument:

    1. 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.
    2. Disable Redirection (logger=None): No logs from the called Actor will be redirected to the parent.
    3. Custom Logger: Pass your own Logger instance 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)
  7. Reboot an Actor on the Apify platform

    master

    Rebooting 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.

  8. Choose the right Crawlee crawler for your task

    master

    Crawlee 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 uses BeautifulSoup for parsing and ImpitHttpClient for HTTP communication.
    • ParselCrawler: Similar to BeautifulSoupCrawler but uses the Parsel library. 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 the Playwright library to provide a full browser automation environment.
  9. Choose a Scrapling fetcher

    master

    Scrapling 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 setting solve_cloudflare=True.
  10. Connect an agent to an LLM

    master

    There are two primary methods for providing an LLM to your agent:

    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_TOKEN automatically injected into the Actor run.
    • Billing: Token usage is billed against your Apify account.
    • Model Selection: Change the model input 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.
  11. Understand changes to default storage IDs in Configuration

    master

    In v3.0, the default storage IDs in Configuration have changed from 'default' to None:

    • Configuration.default_key_value_store_id is now None
    • Configuration.default_dataset_id is now None
    • Configuration.default_request_queue_id is now None

    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.