Actor
apify.Actor
Index
Constructors
Methods
Properties
Constructors
__init__
Create an Actor instance.
Note that you don’t have to do this, all the methods on this class function as classmethods too, and that is their preferred usage.
Parameters
config: Configuration | None = None
The actor configuration to be used. If not passed, a new Configuration instance will be created.
Returns None
Methods
abort
Abort given actor run on the Apify platform using the current user account (determined by the
APIFY_TOKEN
environment variable).Parameters
run_id: str
The ID of the actor run to be aborted.
token: str | None = Nonekeyword-only
The Apify API token to use for this request (defaults to the
APIFY_TOKEN
environment variable).gracefully: bool | None = Nonekeyword-only
If True, the actor run will abort gracefully. It will send
`aborting`
and`persistStates`
events into the run and force-stop the run after 30 seconds. It is helpful in cases where you plan to resurrect the run later.
Returns dict
Info about the aborted actor run
add_webhook
Create an ad-hoc webhook for the current actor run.
This webhook lets you receive a notification when the actor run finished or failed.
Note that webhooks are only supported for actors running on the Apify platform. When running the actor locally, the function will print a warning and have no effect.
For more information about Apify actor webhooks, please see the documentation.
Parameters
event_types: list[WebhookEventType]keyword-only
List of event types that should trigger the webhook. At least one is required.
request_url: strkeyword-only
URL that will be invoked once the webhook is triggered.
payload_template: str | None = Nonekeyword-only
Specification of the payload that will be sent to request_url
ignore_ssl_errors: bool | None = Nonekeyword-only
Whether the webhook should ignore SSL errors returned by request_url
do_not_retry: bool | None = Nonekeyword-only
Whether the webhook should retry sending the payload to request_url upon failure.
idempotency_key: str | None = Nonekeyword-only
A unique identifier of a webhook. You can use it to ensure that you won’t create the same webhook multiple times.
Returns dict
The created webhook
call
Start an actor on the Apify Platform and wait for it to finish before returning.
It waits indefinitely, unless the wait_secs argument is provided.
Parameters
actor_id: str
The ID of the actor to be run.
run_input: Any = None
The input to pass to the actor run.
token: str | None = Nonekeyword-only
The Apify API token to use for this request (defaults to the
APIFY_TOKEN
environment variable).content_type: str | None = Nonekeyword-only
The content type of the input.
build: str | None = Nonekeyword-only
Specifies the actor build to run. It can be either a build tag or build number. By default, the run uses the build specified in the default run configuration for the actor (typically latest).
memory_mbytes: int | None = Nonekeyword-only
Memory limit for the run, in megabytes. By default, the run uses a memory limit specified in the default run configuration for the actor.
timeout_secs: int | None = Nonekeyword-only
Optional timeout for the run, in seconds. By default, the run uses timeout specified in the default run configuration for the actor.
webhooks: list[dict] | None = Nonekeyword-only
Optional webhooks (https://docs.apify.com/webhooks) associated with the actor run, which can be used to receive a notification, e.g. when the actor finished or failed. If you already have a webhook set up for the actor, you do not have to add it again here.
wait_secs: int | None = Nonekeyword-only
The maximum number of seconds the server waits for the run to finish. If not provided, waits indefinitely.
Returns dict | None
Info about the started actor run
call_task
Start an actor task on the Apify Platform and wait for it to finish before returning.
It waits indefinitely, unless the wait_secs argument is provided.
Note that an actor task is a saved input configuration and options for an actor. If you want to run an actor directly rather than an actor task, please use the
Actor.call
Parameters
task_id: str
The ID of the actor to be run.
task_input: dict | None = None
Overrides the input to pass to the actor run.
build: str | None = Nonekeyword-only
Specifies the actor build to run. It can be either a build tag or build number. By default, the run uses the build specified in the default run configuration for the actor (typically latest).
memory_mbytes: int | None = Nonekeyword-only
Memory limit for the run, in megabytes. By default, the run uses a memory limit specified in the default run configuration for the actor.
timeout_secs: int | None = Nonekeyword-only
Optional timeout for the run, in seconds. By default, the run uses timeout specified in the default run configuration for the actor.
webhooks: list[dict] | None = Nonekeyword-only
Optional webhooks (https://docs.apify.com/webhooks) associated with the actor run, which can be used to receive a notification, e.g. when the actor finished or failed. If you already have a webhook set up for the actor, you do not have to add it again here.
wait_secs: int | None = Nonekeyword-only
The maximum number of seconds the server waits for the run to finish. If not provided, waits indefinitely.
token: str | None = Nonekeyword-only
The Apify API token to use for this request (defaults to the
APIFY_TOKEN
environment variable).
Returns dict | None
Info about the started actor run
create_proxy_configuration
Create a ProxyConfiguration object with the passed proxy configuration.
Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking your crawlers based on IP address rate limits or blacklists.
For more details and code examples, see the
ProxyConfiguration
class.Parameters
actor_proxy_input: dict | None = Nonekeyword-only
Proxy configuration field from the actor input, if actor has such input field. If you pass this argument, all the other arguments will be inferred from it.
password: str | None = Nonekeyword-only
Password for the Apify Proxy. If not provided, will use os.environ[‘APIFY_PROXY_PASSWORD’], if available.
groups: list[str] | None = Nonekeyword-only
Proxy groups which the Apify Proxy should use, if provided.
country_code: str | None = Nonekeyword-only
Country which the Apify Proxy should use, if provided.
proxy_urls: list[str] | None = Nonekeyword-only
Custom proxy server URLs which should be rotated through.
new_url_function: Callable[[str | None], str] | Callable[[str | None], Awaitable[str]] | None = Nonekeyword-only
Function which returns a custom proxy URL to be used.
Returns ProxyConfiguration | None
ProxyConfiguration object with the passed configuration, or None, if no proxy should be used based on the configuration.
exit
Exit the actor instance.
This stops the Actor instance. It cancels all the intervals for regularly sending
PERSIST_STATE
events, sends a finalPERSIST_STATE
event, waits for all the event listeners to finish, and stops the event manager.Parameters
exit_code: int = 0keyword-only
The exit code with which the actor should fail (defaults to
0
).event_listeners_timeout_secs: float | None = EVENT_LISTENERS_TIMEOUT_SECSkeyword-only
How long should the actor wait for actor event listeners to finish before exiting.
status_message: str | None = Nonekeyword-only
The final status message that the actor should display.
Returns None
fail
Fail the actor instance.
This performs all the same steps as Actor.exit(), but it additionally sets the exit code to
1
(by default).Parameters
exit_code: int = 1keyword-only
The exit code with which the actor should fail (defaults to
1
).exception: BaseException | None = Nonekeyword-only
The exception with which the actor failed.
status_message: str | None = Nonekeyword-only
The final status message that the actor should display.
Returns None
get_env
Return a dictionary with information parsed from all the
APIFY_XXX
environment variables.For a list of all the environment variables, see the Actor documentation. If some variables are not defined or are invalid, the corresponding value in the resulting dictionary will be None.
Returns dict
get_input
Get the actor input value from the default key-value store associated with the current actor run.
Returns Any
get_system_info
Get the current system info.
Returns dict
get_value
Get a value from the default key-value store associated with the current actor run.
Parameters
key: str
The key of the record which to retrieve.
default_value: Any = None
Default value returned in case the record does not exist.
Returns Any
init
Initialize the actor instance.
This initializes the Actor instance. It configures the right storage client based on whether the actor is running locally or on the Apify platform, it initializes the event manager for processing actor events, and starts an interval for regularly sending
PERSIST_STATE
events, so that the actor can regularly persist its state in response to these events.This method should be called immediately before performing any additional actor actions, and it should be called only once.
Returns None
is_at_home
Return
True
when the actor is running on the Apify platform, andFalse
otherwise (for example when running locally).Returns bool
main
Initialize the actor, run the passed function and finish the actor cleanly.
The
Actor.main()
function is optional and is provided merely for your convenience. It is mainly useful when you’re running your code as an actor on the Apify platform.The
Actor.main()
function performs the following actions:- When running on the Apify platform (i.e.
APIFY_IS_AT_HOME
environment variable is set), it sets up a connection to listen for platform events. For example, to get a notification about an imminent migration to another server. - It invokes the user function passed as the
main_actor_function
parameter. - If the user function was an async function, it awaits it.
- If the user function throws an exception or some other error is encountered, it prints error details to console so that they are stored to the log, and finishes the actor cleanly.
- Finally, it exits the Python process, with zero exit code on success and non-zero on errors.
Parameters
main_actor_function: Callable[[], MainReturnType]
The user function which should be run in the actor
Returns MainReturnType | None
- When running on the Apify platform (i.e.
metamorph
Transform this actor run to an actor run of a different actor.
The platform stops the current actor container and starts a new container with the new actor instead. All the default storages are preserved, and the new input is stored under the
INPUT-METAMORPH-1
key in the same default key-value store.Parameters
target_actor_id: str
ID of the target actor that the run should be transformed into
run_input: Any = None
The input to pass to the new run.
target_actor_build: str | None = Nonekeyword-only
The build of the target actor. It can be either a build tag or build number. By default, the run uses the build specified in the default run configuration for the target actor (typically the latest build).
content_type: str | None = Nonekeyword-only
The content type of the input.
custom_after_sleep_millis: int | None = Nonekeyword-only
How long to sleep for after the metamorph, to wait for the container to be stopped.
Returns None
The actor run data.
new_client
Return a new instance of the Apify API client.
The
ApifyClientAsync
class is provided by the apify-client package, and it is automatically configured using theAPIFY_API_BASE_URL
andAPIFY_TOKEN
environment variables.You can override the token via the available options. That’s useful if you want to use the client as a different Apify user than the SDK internals are using.
Parameters
token: str | None = Nonekeyword-only
The Apify API token
api_url: str | None = Nonekeyword-only
The URL of the Apify API server to which to connect to. Defaults to https://api.apify.com
max_retries: int | None = Nonekeyword-only
How many times to retry a failed request at most
min_delay_between_retries_millis: int | None = Nonekeyword-only
How long will the client wait between retrying requests (increases exponentially from this value)
timeout_secs: int | None = Nonekeyword-only
The socket timeout of the HTTP requests sent to the Apify API
Returns ApifyClientAsync
off
Remove a listener, or all listeners, from an actor event.
Parameters
event_name: ActorEventTypes
The actor event for which to remove listeners.
listener: Callable | None = None
The listener which is supposed to be removed. If not passed, all listeners of this event are removed.
Returns None
on
Add an event listener to the actor’s event manager.
The following events can be emitted:
ActorEventTypes.SYSTEM_INFO
: Emitted every minute, the event data contains info about the resource usage of the actor.ActorEventTypes.MIGRATING
: Emitted when the actor running on the Apify platform is going to be migrated to another worker server soon. You can use it to persist the state of the actor and gracefully stop your in-progress tasks, so that they are not interrupted by the migration..ActorEventTypes.PERSIST_STATE
: Emitted in regular intervals (by default 60 seconds) to notify the actor that it should persist its state, in order to avoid repeating all work when the actor restarts. This event is automatically emitted together with the migrating event, in which case theisMigrating
flag in the event data is set to True, otherwise the flag is False. Note that this event is provided merely for your convenience, you can achieve the same effect using an interval and listening for the migrating event.ActorEventTypes.ABORTING
: When a user aborts an actor run on the Apify platform, they can choose to abort it gracefully, to allow the actor some time before getting terminated. This graceful abort emits the aborting event, which you can use to clean up the actor state.
Parameters
event_name: ActorEventTypes
The actor event for which to listen to.
listener: Callable
The function which is to be called when the event is emitted (can be async).
Returns Callable
open_dataset
Open a dataset.
Datasets are used to store structured data where each object stored has the same attributes, such as online store products or real estate offers. The actual data is stored either on the local filesystem or in the Apify cloud.
Parameters
id: str | None = Nonekeyword-only
ID of the dataset to be opened. If neither
id
norname
are provided, the method returns the default dataset associated with the actor run.name: str | None = Nonekeyword-only
Name of the dataset to be opened. If neither
id
norname
are provided, the method returns the default dataset associated with the actor run.force_cloud: bool = Falsekeyword-only
If set to
True
then the Apify cloud storage is always used. This way it is possible to combine local and cloud storage.
Returns Dataset
An instance of the
Dataset
class for the given ID or name.
open_key_value_store
Open a key-value store.
Key-value stores are used to store records or files, along with their MIME content type. The records are stored and retrieved using a unique key. The actual data is stored either on a local filesystem or in the Apify cloud.
Parameters
id: str | None = Nonekeyword-only
ID of the key-value store to be opened. If neither
id
norname
are provided, the method returns the default key-value store associated with the actor run.name: str | None = Nonekeyword-only
Name of the key-value store to be opened. If neither
id
norname
are provided, the method returns the default key-value store associated with the actor run.force_cloud: bool = Falsekeyword-only
If set to
True
then the Apify cloud storage is always used. This way it is possible to combine local and cloud storage.
Returns KeyValueStore
An instance of the
KeyValueStore
class for the given ID or name.
open_request_queue
Open a request queue.
Request queue represents a queue of URLs to crawl, which is stored either on local filesystem or in the Apify cloud. The queue is used for deep crawling of websites, where you start with several URLs and then recursively follow links to other pages. The data structure supports both breadth-first and depth-first crawling orders.
Parameters
id: str | None = Nonekeyword-only
ID of the request queue to be opened. If neither
id
norname
are provided, the method returns the default request queue associated with the actor run.name: str | None = Nonekeyword-only
Name of the request queue to be opened. If neither
id
norname
are provided, the method returns the default request queue associated with the actor run.force_cloud: bool = Falsekeyword-only
If set to
True
then the Apify cloud storage is always used. This way it is possible to combine local and cloud storage.
Returns RequestQueue
An instance of the
RequestQueue
class for the given ID or name.
push_data
Store an object or a list of objects to the default dataset of the current actor run.
Parameters
data: Any
The data to push to the default dataset.
Returns None
reboot
Internally reboot this actor.
The system stops the current container and starts a new one, with the same run ID and default storages.
Parameters
event_listeners_timeout_secs: int | None = EVENT_LISTENERS_TIMEOUT_SECSkeyword-only
How long should the actor wait for actor event listeners to finish before exiting
custom_after_sleep_millis: int | None = Nonekeyword-only
How long to sleep for after the reboot, to wait for the container to be stopped.
Returns None
set_status_message
Set the status message for the current actor run.
Parameters
status_message: str
The status message to set to the run.
is_terminal: bool | None = Nonekeyword-only
Set this flag to True if this is the final status message of the Actor run.
Returns dict | None
The updated actor run object
set_value
Set or delete a value in the default key-value store associated with the current actor run.
Parameters
key: str
The key of the record which to set.
value: Any
The value of the record which to set, or None, if the record should be deleted.
content_type: str | None = Nonekeyword-only
The content type which should be set to the value.
Returns None
start
Run an actor on the Apify platform.
Unlike
Actor.call
, this method just starts the run without waiting for finish.Parameters
actor_id: str
The ID of the actor to be run.
run_input: Any = None
The input to pass to the actor run.
token: str | None = Nonekeyword-only
The Apify API token to use for this request (defaults to the
APIFY_TOKEN
environment variable).content_type: str | None = Nonekeyword-only
The content type of the input.
build: str | None = Nonekeyword-only
Specifies the actor build to run. It can be either a build tag or build number. By default, the run uses the build specified in the default run configuration for the actor (typically latest).
memory_mbytes: int | None = Nonekeyword-only
Memory limit for the run, in megabytes. By default, the run uses a memory limit specified in the default run configuration for the actor.
timeout_secs: int | None = Nonekeyword-only
Optional timeout for the run, in seconds. By default, the run uses timeout specified in the default run configuration for the actor.
wait_for_finish: int | None = Nonekeyword-only
The maximum number of seconds the server waits for the run to finish. By default, it is 0, the maximum value is 300.
webhooks: list[dict] | None = Nonekeyword-only
Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks) associated with the actor run which can be used to receive a notification, e.g. when the actor finished or failed. If you already have a webhook set up for the actor or task, you do not have to add it again here. Each webhook is represented by a dictionary containing these items: *
`event_types`
: list of`WebhookEventType`
values which trigger the webhook *`request_url`
: URL to which to send the webhook HTTP request *`payload_template`
(optional): Optional template for the request payload
Returns dict
Info about the started actor run
Properties
apify_client
The ApifyClientAsync instance the Actor instance uses.
config
The Configuration instance the Actor instance uses.
event_manager
The EventManager instance the Actor instance uses.
log
The logging.Logger instance the Actor uses.
The main class of the SDK, through which all the actor operations should be done.