apify 2.3.0b2__py3-none-any.whl → 2.3.1b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of apify might be problematic. Click here for more details.

apify/_actor.py CHANGED
@@ -24,6 +24,7 @@ from crawlee.events import (
24
24
  EventSystemInfoData,
25
25
  )
26
26
 
27
+ from apify._charging import ChargeResult, ChargingManager, ChargingManagerImplementation
27
28
  from apify._configuration import Configuration
28
29
  from apify._consts import EVENT_LISTENERS_TIMEOUT
29
30
  from apify._crypto import decrypt_input_secrets, load_private_key
@@ -97,6 +98,8 @@ class _ActorType:
97
98
  )
98
99
  )
99
100
 
101
+ self._charging_manager = ChargingManagerImplementation(self._configuration, self._apify_client)
102
+
100
103
  self._is_initialized = False
101
104
 
102
105
  @ignore_docs
@@ -227,6 +230,10 @@ class _ActorType:
227
230
  # https://github.com/apify/apify-sdk-python/issues/146
228
231
 
229
232
  await self._event_manager.__aenter__()
233
+ self.log.debug('Event manager initialized')
234
+
235
+ await self._charging_manager.__aenter__()
236
+ self.log.debug('Charging manager initialized')
230
237
 
231
238
  self._is_initialized = True
232
239
  _ActorType._is_any_instance_initialized = True
@@ -269,6 +276,7 @@ class _ActorType:
269
276
  await self._event_manager.wait_for_all_listeners_to_complete(timeout=event_listeners_timeout)
270
277
 
271
278
  await self._event_manager.__aexit__(None, None, None)
279
+ await self._charging_manager.__aexit__(None, None, None)
272
280
 
273
281
  await asyncio.wait_for(finalize(), cleanup_timeout.total_seconds())
274
282
  self._is_initialized = False
@@ -452,19 +460,46 @@ class _ActorType:
452
460
  storage_client=storage_client,
453
461
  )
454
462
 
455
- async def push_data(self, data: dict | list[dict]) -> None:
463
+ @overload
464
+ async def push_data(self, data: dict | list[dict]) -> None: ...
465
+ @overload
466
+ async def push_data(self, data: dict | list[dict], charged_event_name: str) -> ChargeResult: ...
467
+ async def push_data(self, data: dict | list[dict], charged_event_name: str | None = None) -> ChargeResult | None:
456
468
  """Store an object or a list of objects to the default dataset of the current Actor run.
457
469
 
458
470
  Args:
459
471
  data: The data to push to the default dataset.
472
+ charged_event_name: If provided and if the Actor uses the pay-per-event pricing model,
473
+ the method will attempt to charge for the event for each pushed item.
460
474
  """
461
475
  self._raise_if_not_initialized()
462
476
 
463
477
  if not data:
464
- return
478
+ return None
479
+
480
+ data = data if isinstance(data, list) else [data]
481
+
482
+ max_charged_count = (
483
+ self._charging_manager.calculate_max_event_charge_count_within_limit(charged_event_name)
484
+ if charged_event_name is not None
485
+ else None
486
+ )
465
487
 
466
488
  dataset = await self.open_dataset()
467
- await dataset.push_data(data)
489
+
490
+ if max_charged_count is not None and len(data) > max_charged_count:
491
+ # Push as many items as we can charge for
492
+ await dataset.push_data(data[:max_charged_count])
493
+ else:
494
+ await dataset.push_data(data)
495
+
496
+ if charged_event_name:
497
+ return await self._charging_manager.charge(
498
+ event_name=charged_event_name,
499
+ count=min(max_charged_count, len(data)) if max_charged_count is not None else len(data),
500
+ )
501
+
502
+ return None
468
503
 
469
504
  async def get_input(self) -> Any:
470
505
  """Get the Actor input value from the default key-value store associated with the current Actor run."""
@@ -513,6 +548,23 @@ class _ActorType:
513
548
  key_value_store = await self.open_key_value_store()
514
549
  return await key_value_store.set_value(key, value, content_type=content_type)
515
550
 
551
+ def get_charging_manager(self) -> ChargingManager:
552
+ """Retrieve the charging manager to access granular pricing information."""
553
+ self._raise_if_not_initialized()
554
+ return self._charging_manager
555
+
556
+ async def charge(self, event_name: str, count: int = 1) -> ChargeResult:
557
+ """Charge for a specified number of events - sub-operations of the Actor.
558
+
559
+ This is relevant only for the pay-per-event pricing model.
560
+
561
+ Args:
562
+ event_name: Name of the event to be charged for.
563
+ count: Number of events to charge for.
564
+ """
565
+ self._raise_if_not_initialized()
566
+ return await self._charging_manager.charge(event_name, count)
567
+
516
568
  @overload
517
569
  def on(
518
570
  self, event_name: Literal[Event.PERSIST_STATE], listener: EventListener[EventPersistStateData]
apify/_charging.py ADDED
@@ -0,0 +1,318 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timezone
6
+ from decimal import Decimal
7
+ from typing import TYPE_CHECKING, Protocol, Union
8
+
9
+ from pydantic import TypeAdapter
10
+
11
+ from apify_shared.utils import ignore_docs
12
+ from crawlee._utils.context import ensure_context
13
+
14
+ from apify._models import ActorRun, PricingModel
15
+ from apify._utils import docs_group
16
+ from apify.log import logger
17
+ from apify.storages import Dataset
18
+
19
+ if TYPE_CHECKING:
20
+ from types import TracebackType
21
+
22
+ from apify_client import ApifyClientAsync
23
+
24
+ from apify._configuration import Configuration
25
+
26
+
27
+ run_validator: TypeAdapter[ActorRun | None] = TypeAdapter(Union[ActorRun, None])
28
+
29
+
30
+ @docs_group('Interfaces')
31
+ class ChargingManager(Protocol):
32
+ """Provides fine-grained access to pay-per-event functionality."""
33
+
34
+ async def charge(self, event_name: str, count: int = 1) -> ChargeResult:
35
+ """Charge for a specified number of events - sub-operations of the Actor.
36
+
37
+ This is relevant only for the pay-per-event pricing model.
38
+
39
+ Args:
40
+ event_name: Name of the event to be charged for.
41
+ count: Number of events to charge for.
42
+ """
43
+
44
+ def calculate_total_charged_amount(self) -> Decimal:
45
+ """Calculate the total amount of money charged for pay-per-event events so far."""
46
+
47
+ def calculate_max_event_charge_count_within_limit(self, event_name: str) -> int | None:
48
+ """Calculate how many instances of an event can be charged before we reach the configured limit.
49
+
50
+ Args:
51
+ event_name: Name of the inspected event.
52
+ """
53
+
54
+ def get_pricing_info(self) -> ActorPricingInfo:
55
+ """Retrieve detailed information about the effective pricing of the current Actor run.
56
+
57
+ This can be used for instance when your code needs to support multiple pricing models in transition periods.
58
+ """
59
+
60
+
61
+ @docs_group('Data structures')
62
+ @dataclass(frozen=True)
63
+ class ChargeResult:
64
+ """Result of the `ChargingManager.charge` method."""
65
+
66
+ event_charge_limit_reached: bool
67
+ """If true, no more events of this type can be charged within the limit."""
68
+
69
+ charged_count: int
70
+ """Total amount of charged events - may be lower than the requested amount."""
71
+
72
+ chargeable_within_limit: dict[str, int | None]
73
+ """How many events of each known type can still be charged within the limit."""
74
+
75
+
76
+ @docs_group('Data structures')
77
+ @dataclass
78
+ class ActorPricingInfo:
79
+ """Result of the `ChargingManager.get_pricing_info` method."""
80
+
81
+ pricing_model: PricingModel | None
82
+ """The currently effective pricing model."""
83
+
84
+ max_total_charge_usd: Decimal
85
+ """A configured limit for the total charged amount - if you exceed it, you won't receive more money than this."""
86
+
87
+ is_pay_per_event: bool
88
+ """A shortcut - true if the Actor runs with the pay-per-event pricing model."""
89
+
90
+ per_event_prices: dict[str, Decimal]
91
+ """Price of every known event type."""
92
+
93
+
94
+ @ignore_docs
95
+ class ChargingManagerImplementation(ChargingManager):
96
+ """Implementation of the `ChargingManager` Protocol - this is only meant to be instantiated internally."""
97
+
98
+ LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log'
99
+
100
+ def __init__(self, configuration: Configuration, client: ApifyClientAsync) -> None:
101
+ self._max_total_charge_usd = configuration.max_total_charge_usd or Decimal('inf')
102
+ self._is_at_home = configuration.is_at_home
103
+ self._actor_run_id = configuration.actor_run_id
104
+ self._purge_charging_log_dataset = configuration.purge_on_start
105
+ self._pricing_model: PricingModel | None = None
106
+
107
+ if configuration.test_pay_per_event:
108
+ if self._is_at_home:
109
+ raise ValueError(
110
+ 'Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported '
111
+ 'in a local development environment'
112
+ )
113
+
114
+ self._pricing_model = 'PAY_PER_EVENT'
115
+
116
+ self._client = client
117
+ self._charging_log_dataset: Dataset | None = None
118
+
119
+ self._charging_state: dict[str, ChargingStateItem] = {}
120
+ self._pricing_info: dict[str, PricingInfoItem] = {}
121
+
122
+ self._not_ppe_warning_printed = False
123
+ self.active = False
124
+
125
+ async def __aenter__(self) -> None:
126
+ """Initialize the charging manager - this is called by the `Actor` class and shouldn't be invoked manually."""
127
+ self.active = True
128
+
129
+ if self._is_at_home:
130
+ # Running on the Apify platform - fetch pricing info for the current run.
131
+
132
+ if self._actor_run_id is None:
133
+ raise RuntimeError('Actor run ID not found even though the Actor is running on Apify')
134
+
135
+ run = run_validator.validate_python(await self._client.run(self._actor_run_id).get())
136
+ if run is None:
137
+ raise RuntimeError('Actor run not found')
138
+
139
+ if run.pricing_info is not None:
140
+ self._pricing_model = run.pricing_info.pricing_model
141
+
142
+ if run.pricing_info.pricing_model == 'PAY_PER_EVENT':
143
+ for event_name, event_pricing in run.pricing_info.pricing_per_event.actor_charge_events.items():
144
+ self._pricing_info[event_name] = PricingInfoItem(
145
+ price=event_pricing.event_price_usd,
146
+ title=event_pricing.event_title,
147
+ )
148
+
149
+ self._max_total_charge_usd = run.options.max_total_charge_usd or self._max_total_charge_usd
150
+
151
+ for event_name, count in (run.charged_event_counts or {}).items():
152
+ price = self._pricing_info.get(event_name, PricingInfoItem(Decimal(), title='')).price
153
+ self._charging_state[event_name] = ChargingStateItem(
154
+ charge_count=count,
155
+ total_charged_amount=count * price,
156
+ )
157
+
158
+ if not self._is_at_home and self._pricing_model == 'PAY_PER_EVENT':
159
+ # We are not running on the Apify platform, but PPE is enabled for testing - open a dataset that
160
+ # will contain a log of all charge calls for debugging purposes.
161
+
162
+ if self._purge_charging_log_dataset:
163
+ dataset = await Dataset.open(name=self.LOCAL_CHARGING_LOG_DATASET_NAME)
164
+ await dataset.drop()
165
+
166
+ self._charging_log_dataset = await Dataset.open(name=self.LOCAL_CHARGING_LOG_DATASET_NAME)
167
+
168
+ async def __aexit__(
169
+ self,
170
+ exc_type: type[BaseException] | None,
171
+ exc_value: BaseException | None,
172
+ exc_traceback: TracebackType | None,
173
+ ) -> None:
174
+ if not self.active:
175
+ raise RuntimeError('Exiting an uninitialized ChargingManager')
176
+
177
+ self.active = False
178
+
179
+ @ensure_context
180
+ async def charge(self, event_name: str, count: int = 1) -> ChargeResult:
181
+ def calculate_chargeable() -> dict[str, int | None]:
182
+ """Calculate the maximum number of events of each type that can be charged within the current budget."""
183
+ return {
184
+ event_name: self.calculate_max_event_charge_count_within_limit(event_name)
185
+ for event_name in self._pricing_info
186
+ }
187
+
188
+ # For runs that do not use the pay-per-event pricing model, just print a warning and return
189
+ if self._pricing_model != 'PAY_PER_EVENT':
190
+ if not self._not_ppe_warning_printed:
191
+ logger.warning(
192
+ 'Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing'
193
+ )
194
+ self._not_ppe_warning_printed = True
195
+
196
+ return ChargeResult(
197
+ event_charge_limit_reached=False,
198
+ charged_count=0,
199
+ chargeable_within_limit=calculate_chargeable(),
200
+ )
201
+
202
+ # START OF CRITICAL SECTION - no awaits here
203
+
204
+ # Determine the maximum amount of events that can be charged within the budget
205
+ charged_count = min(count, self.calculate_max_event_charge_count_within_limit(event_name) or count)
206
+
207
+ if charged_count == 0:
208
+ return ChargeResult(
209
+ event_charge_limit_reached=True,
210
+ charged_count=0,
211
+ chargeable_within_limit=calculate_chargeable(),
212
+ )
213
+
214
+ pricing_info = self._pricing_info.get(
215
+ event_name,
216
+ PricingInfoItem(
217
+ price=Decimal()
218
+ if self._is_at_home
219
+ else Decimal(
220
+ '1'
221
+ ), # Use a nonzero price for local development so that the maximum budget can be reached,
222
+ title=f"Unknown event '{event_name}'",
223
+ ),
224
+ )
225
+
226
+ # Update the charging state
227
+ self._charging_state.setdefault(event_name, ChargingStateItem(0, Decimal()))
228
+ self._charging_state[event_name].charge_count += charged_count
229
+ self._charging_state[event_name].total_charged_amount += charged_count * pricing_info.price
230
+
231
+ # END OF CRITICAL SECTION
232
+
233
+ # If running on the platform, call the charge endpoint
234
+ if self._is_at_home:
235
+ if self._actor_run_id is None:
236
+ raise RuntimeError('Actor run ID not configured')
237
+
238
+ if event_name in self._pricing_info:
239
+ await self._client.run(self._actor_run_id).charge(event_name, charged_count)
240
+ else:
241
+ logger.warning(f"Attempting to charge for an unknown event '{event_name}'")
242
+
243
+ # Log the charged operation (if enabled)
244
+ if self._charging_log_dataset:
245
+ await self._charging_log_dataset.push_data(
246
+ {
247
+ 'event_name': event_name,
248
+ 'event_title': pricing_info.title,
249
+ 'event_price_usd': round(pricing_info.price, 3),
250
+ 'charged_count': charged_count,
251
+ 'timestamp': datetime.now(timezone.utc).isoformat(),
252
+ }
253
+ )
254
+
255
+ # If it is not possible to charge the full amount, log that fact
256
+ if charged_count < count:
257
+ subject = 'instance' if count == 1 else 'instances'
258
+ logger.info(
259
+ f"Charging {count} ${subject} of '{event_name}' event would exceed max_total_charge_usd "
260
+ '- only {charged_count} events were charged'
261
+ )
262
+
263
+ max_charge_count = self.calculate_max_event_charge_count_within_limit(event_name)
264
+
265
+ return ChargeResult(
266
+ event_charge_limit_reached=max_charge_count is not None and max_charge_count <= 0,
267
+ charged_count=charged_count,
268
+ chargeable_within_limit=calculate_chargeable(),
269
+ )
270
+
271
+ @ensure_context
272
+ def calculate_total_charged_amount(self) -> Decimal:
273
+ return sum(
274
+ (item.total_charged_amount for item in self._charging_state.values()),
275
+ start=Decimal(),
276
+ )
277
+
278
+ @ensure_context
279
+ def calculate_max_event_charge_count_within_limit(self, event_name: str) -> int | None:
280
+ pricing_info = self._pricing_info.get(event_name)
281
+
282
+ if pricing_info is not None:
283
+ price = pricing_info.price
284
+ elif not self._is_at_home:
285
+ price = Decimal('1') # Use a nonzero price for local development so that the maximum budget can be reached
286
+ else:
287
+ price = Decimal()
288
+
289
+ if not price:
290
+ return None
291
+
292
+ result = (self._max_total_charge_usd - self.calculate_total_charged_amount()) / price
293
+ return math.floor(result) if result.is_finite() else None
294
+
295
+ @ensure_context
296
+ def get_pricing_info(self) -> ActorPricingInfo:
297
+ return ActorPricingInfo(
298
+ pricing_model=self._pricing_model,
299
+ is_pay_per_event=self._pricing_model == 'PAY_PER_EVENT',
300
+ max_total_charge_usd=self._max_total_charge_usd
301
+ if self._max_total_charge_usd is not None
302
+ else Decimal('inf'),
303
+ per_event_prices={
304
+ event_name: pricing_info.price for event_name, pricing_info in self._pricing_info.items()
305
+ },
306
+ )
307
+
308
+
309
+ @dataclass
310
+ class ChargingStateItem:
311
+ charge_count: int
312
+ total_charged_amount: Decimal
313
+
314
+
315
+ @dataclass
316
+ class PricingInfoItem:
317
+ price: Decimal
318
+ title: str
apify/_configuration.py CHANGED
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from datetime import datetime, timedelta
4
+ from decimal import Decimal
4
5
  from logging import getLogger
5
6
  from typing import Annotated, Any
6
7
 
@@ -212,7 +213,7 @@ class Configuration(CrawleeConfiguration):
212
213
  ] = None
213
214
 
214
215
  max_total_charge_usd: Annotated[
215
- float | None,
216
+ Decimal | None,
216
217
  Field(
217
218
  alias='actor_max_total_charge_usd',
218
219
  description='For pay-per-event Actors, the user-set limit on total charges. Do not exceed this limit',
@@ -220,6 +221,14 @@ class Configuration(CrawleeConfiguration):
220
221
  BeforeValidator(lambda val: val or None),
221
222
  ] = None
222
223
 
224
+ test_pay_per_event: Annotated[
225
+ bool,
226
+ Field(
227
+ alias='actor_test_pay_per_event',
228
+ description='Enable pay-per-event functionality for local development',
229
+ ),
230
+ ] = False
231
+
223
232
  meta_origin: Annotated[
224
233
  str | None,
225
234
  Field(
apify/_models.py CHANGED
@@ -1,7 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from datetime import datetime, timedelta
4
- from typing import Annotated
4
+ from decimal import Decimal
5
+ from typing import TYPE_CHECKING, Annotated, Literal
5
6
 
6
7
  from pydantic import BaseModel, BeforeValidator, ConfigDict, Field
7
8
 
@@ -11,6 +12,9 @@ from crawlee._utils.urls import validate_http_url
11
12
 
12
13
  from apify._utils import docs_group
13
14
 
15
+ if TYPE_CHECKING:
16
+ from typing_extensions import TypeAlias
17
+
14
18
 
15
19
  @docs_group('Data structures')
16
20
  class Webhook(BaseModel):
@@ -42,7 +46,7 @@ class ActorRunMeta(BaseModel):
42
46
  class ActorRunStats(BaseModel):
43
47
  __model_config__ = ConfigDict(populate_by_name=True)
44
48
 
45
- input_body_len: Annotated[int, Field(alias='inputBodyLen')]
49
+ input_body_len: Annotated[int | None, Field(alias='inputBodyLen')] = None
46
50
  restart_count: Annotated[int, Field(alias='restartCount')]
47
51
  resurrect_count: Annotated[int, Field(alias='resurrectCount')]
48
52
  mem_avg_bytes: Annotated[float | None, Field(alias='memAvgBytes')] = None
@@ -67,6 +71,7 @@ class ActorRunOptions(BaseModel):
67
71
  timeout: Annotated[timedelta, Field(alias='timeoutSecs')]
68
72
  memory_mbytes: Annotated[int, Field(alias='memoryMbytes')]
69
73
  disk_mbytes: Annotated[int, Field(alias='diskMbytes')]
74
+ max_total_charge_usd: Annotated[Decimal | None, Field(alias='maxTotalChargeUsd')] = None
70
75
 
71
76
 
72
77
  @docs_group('Data structures')
@@ -115,3 +120,55 @@ class ActorRun(BaseModel):
115
120
  usage: Annotated[ActorRunUsage | None, Field(alias='usage')] = None
116
121
  usage_total_usd: Annotated[float | None, Field(alias='usageTotalUsd')] = None
117
122
  usage_usd: Annotated[ActorRunUsage | None, Field(alias='usageUsd')] = None
123
+ pricing_info: Annotated[
124
+ FreeActorPricingInfo
125
+ | FlatPricePerMonthActorPricingInfo
126
+ | PricePerDatasetItemActorPricingInfo
127
+ | PayPerEventActorPricingInfo
128
+ | None,
129
+ Field(alias='pricingInfo', discriminator='pricing_model'),
130
+ ] = None
131
+ charged_event_counts: Annotated[
132
+ dict[str, int] | None,
133
+ Field(alias='chargedEventCounts'),
134
+ ] = None
135
+
136
+
137
+ class FreeActorPricingInfo(BaseModel):
138
+ pricing_model: Annotated[Literal['FREE'], Field(alias='pricingModel')]
139
+
140
+
141
+ class FlatPricePerMonthActorPricingInfo(BaseModel):
142
+ pricing_model: Annotated[Literal['FLAT_PRICE_PER_MONTH'], Field(alias='pricingModel')]
143
+ trial_minutes: Annotated[int | None, Field(alias='trialMinutes')] = None
144
+ price_per_unit_usd: Annotated[Decimal, Field(alias='pricePerUnitUsd')]
145
+
146
+
147
+ class PricePerDatasetItemActorPricingInfo(BaseModel):
148
+ pricing_model: Annotated[Literal['PRICE_PER_DATASET_ITEM'], Field(alias='pricingModel')]
149
+ unit_name: Annotated[str | None, Field(alias='unitName')] = None
150
+ price_per_unit_usd: Annotated[Decimal, Field(alias='pricePerUnitUsd')]
151
+
152
+
153
+ class ActorChargeEvent(BaseModel):
154
+ event_price_usd: Annotated[Decimal, Field(alias='eventPriceUsd')]
155
+ event_title: Annotated[str, Field(alias='eventTitle')]
156
+ event_description: Annotated[str | None, Field(alias='eventDescription')] = None
157
+
158
+
159
+ class PricingPerEvent(BaseModel):
160
+ actor_charge_events: Annotated[dict[str, ActorChargeEvent], Field(alias='actorChargeEvents')]
161
+
162
+
163
+ class PayPerEventActorPricingInfo(BaseModel):
164
+ pricing_model: Annotated[Literal['PAY_PER_EVENT'], Field(alias='pricingModel')]
165
+ pricing_per_event: Annotated[PricingPerEvent, Field(alias='pricingPerEvent')]
166
+ minimal_max_total_charge_usd: Annotated[Decimal | None, Field(alias='minimalMaxTotalChargeUsd')] = None
167
+
168
+
169
+ PricingModel: TypeAlias = Literal[
170
+ 'FREE',
171
+ 'FLAT_PRICE_PER_MONTH',
172
+ 'PRICE_PER_DATASET_ITEM',
173
+ 'PAY_PER_EVENT',
174
+ ]
apify/_utils.py CHANGED
@@ -27,7 +27,7 @@ def is_running_in_ipython() -> bool:
27
27
  return getattr(builtins, '__IPYTHON__', False)
28
28
 
29
29
 
30
- GroupName = Literal['Classes', 'Abstract classes', 'Data structures', 'Errors', 'Functions']
30
+ GroupName = Literal['Classes', 'Abstract classes', 'Interfaces', 'Data structures', 'Errors', 'Functions']
31
31
 
32
32
 
33
33
  def docs_group(group_name: GroupName) -> Callable: # noqa: ARG001
@@ -0,0 +1,411 @@
1
+ Metadata-Version: 2.4
2
+ Name: apify
3
+ Version: 2.3.1b1
4
+ Summary: Apify SDK for Python
5
+ Project-URL: Homepage, https://docs.apify.com/sdk/python/
6
+ Project-URL: Apify homepage, https://apify.com
7
+ Project-URL: Changelog, https://docs.apify.com/sdk/python/docs/changelog
8
+ Project-URL: Documentation, https://docs.apify.com/sdk/python/
9
+ Project-URL: Issue tracker, https://github.com/apify/apify-sdk-python/issues
10
+ Project-URL: Repository, https://github.com/apify/apify-sdk-python
11
+ Author-email: "Apify Technologies s.r.o." <support@apify.com>
12
+ License: Apache License
13
+ Version 2.0, January 2004
14
+ http://www.apache.org/licenses/
15
+
16
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
17
+
18
+ 1. Definitions.
19
+
20
+ "License" shall mean the terms and conditions for use, reproduction,
21
+ and distribution as defined by Sections 1 through 9 of this document.
22
+
23
+ "Licensor" shall mean the copyright owner or entity authorized by
24
+ the copyright owner that is granting the License.
25
+
26
+ "Legal Entity" shall mean the union of the acting entity and all
27
+ other entities that control, are controlled by, or are under common
28
+ control with that entity. For the purposes of this definition,
29
+ "control" means (i) the power, direct or indirect, to cause the
30
+ direction or management of such entity, whether by contract or
31
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
32
+ outstanding shares, or (iii) beneficial ownership of such entity.
33
+
34
+ "You" (or "Your") shall mean an individual or Legal Entity
35
+ exercising permissions granted by this License.
36
+
37
+ "Source" form shall mean the preferred form for making modifications,
38
+ including but not limited to software source code, documentation
39
+ source, and configuration files.
40
+
41
+ "Object" form shall mean any form resulting from mechanical
42
+ transformation or translation of a Source form, including but
43
+ not limited to compiled object code, generated documentation,
44
+ and conversions to other media types.
45
+
46
+ "Work" shall mean the work of authorship, whether in Source or
47
+ Object form, made available under the License, as indicated by a
48
+ copyright notice that is included in or attached to the work
49
+ (an example is provided in the Appendix below).
50
+
51
+ "Derivative Works" shall mean any work, whether in Source or Object
52
+ form, that is based on (or derived from) the Work and for which the
53
+ editorial revisions, annotations, elaborations, or other modifications
54
+ represent, as a whole, an original work of authorship. For the purposes
55
+ of this License, Derivative Works shall not include works that remain
56
+ separable from, or merely link (or bind by name) to the interfaces of,
57
+ the Work and Derivative Works thereof.
58
+
59
+ "Contribution" shall mean any work of authorship, including
60
+ the original version of the Work and any modifications or additions
61
+ to that Work or Derivative Works thereof, that is intentionally
62
+ submitted to Licensor for inclusion in the Work by the copyright owner
63
+ or by an individual or Legal Entity authorized to submit on behalf of
64
+ the copyright owner. For the purposes of this definition, "submitted"
65
+ means any form of electronic, verbal, or written communication sent
66
+ to the Licensor or its representatives, including but not limited to
67
+ communication on electronic mailing lists, source code control systems,
68
+ and issue tracking systems that are managed by, or on behalf of, the
69
+ Licensor for the purpose of discussing and improving the Work, but
70
+ excluding communication that is conspicuously marked or otherwise
71
+ designated in writing by the copyright owner as "Not a Contribution."
72
+
73
+ "Contributor" shall mean Licensor and any individual or Legal Entity
74
+ on behalf of whom a Contribution has been received by Licensor and
75
+ subsequently incorporated within the Work.
76
+
77
+ 2. Grant of Copyright License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ copyright license to reproduce, prepare Derivative Works of,
81
+ publicly display, publicly perform, sublicense, and distribute the
82
+ Work and such Derivative Works in Source or Object form.
83
+
84
+ 3. Grant of Patent License. Subject to the terms and conditions of
85
+ this License, each Contributor hereby grants to You a perpetual,
86
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
87
+ (except as stated in this section) patent license to make, have made,
88
+ use, offer to sell, sell, import, and otherwise transfer the Work,
89
+ where such license applies only to those patent claims licensable
90
+ by such Contributor that are necessarily infringed by their
91
+ Contribution(s) alone or by combination of their Contribution(s)
92
+ with the Work to which such Contribution(s) was submitted. If You
93
+ institute patent litigation against any entity (including a
94
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
95
+ or a Contribution incorporated within the Work constitutes direct
96
+ or contributory patent infringement, then any patent licenses
97
+ granted to You under this License for that Work shall terminate
98
+ as of the date such litigation is filed.
99
+
100
+ 4. Redistribution. You may reproduce and distribute copies of the
101
+ Work or Derivative Works thereof in any medium, with or without
102
+ modifications, and in Source or Object form, provided that You
103
+ meet the following conditions:
104
+
105
+ (a) You must give any other recipients of the Work or
106
+ Derivative Works a copy of this License; and
107
+
108
+ (b) You must cause any modified files to carry prominent notices
109
+ stating that You changed the files; and
110
+
111
+ (c) You must retain, in the Source form of any Derivative Works
112
+ that You distribute, all copyright, patent, trademark, and
113
+ attribution notices from the Source form of the Work,
114
+ excluding those notices that do not pertain to any part of
115
+ the Derivative Works; and
116
+
117
+ (d) If the Work includes a "NOTICE" text file as part of its
118
+ distribution, then any Derivative Works that You distribute must
119
+ include a readable copy of the attribution notices contained
120
+ within such NOTICE file, excluding those notices that do not
121
+ pertain to any part of the Derivative Works, in at least one
122
+ of the following places: within a NOTICE text file distributed
123
+ as part of the Derivative Works; within the Source form or
124
+ documentation, if provided along with the Derivative Works; or,
125
+ within a display generated by the Derivative Works, if and
126
+ wherever such third-party notices normally appear. The contents
127
+ of the NOTICE file are for informational purposes only and
128
+ do not modify the License. You may add Your own attribution
129
+ notices within Derivative Works that You distribute, alongside
130
+ or as an addendum to the NOTICE text from the Work, provided
131
+ that such additional attribution notices cannot be construed
132
+ as modifying the License.
133
+
134
+ You may add Your own copyright statement to Your modifications and
135
+ may provide additional or different license terms and conditions
136
+ for use, reproduction, or distribution of Your modifications, or
137
+ for any such Derivative Works as a whole, provided Your use,
138
+ reproduction, and distribution of the Work otherwise complies with
139
+ the conditions stated in this License.
140
+
141
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
142
+ any Contribution intentionally submitted for inclusion in the Work
143
+ by You to the Licensor shall be under the terms and conditions of
144
+ this License, without any additional terms or conditions.
145
+ Notwithstanding the above, nothing herein shall supersede or modify
146
+ the terms of any separate license agreement you may have executed
147
+ with Licensor regarding such Contributions.
148
+
149
+ 6. Trademarks. This License does not grant permission to use the trade
150
+ names, trademarks, service marks, or product names of the Licensor,
151
+ except as required for reasonable and customary use in describing the
152
+ origin of the Work and reproducing the content of the NOTICE file.
153
+
154
+ 7. Disclaimer of Warranty. Unless required by applicable law or
155
+ agreed to in writing, Licensor provides the Work (and each
156
+ Contributor provides its Contributions) on an "AS IS" BASIS,
157
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
158
+ implied, including, without limitation, any warranties or conditions
159
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
160
+ PARTICULAR PURPOSE. You are solely responsible for determining the
161
+ appropriateness of using or redistributing the Work and assume any
162
+ risks associated with Your exercise of permissions under this License.
163
+
164
+ 8. Limitation of Liability. In no event and under no legal theory,
165
+ whether in tort (including negligence), contract, or otherwise,
166
+ unless required by applicable law (such as deliberate and grossly
167
+ negligent acts) or agreed to in writing, shall any Contributor be
168
+ liable to You for damages, including any direct, indirect, special,
169
+ incidental, or consequential damages of any character arising as a
170
+ result of this License or out of the use or inability to use the
171
+ Work (including but not limited to damages for loss of goodwill,
172
+ work stoppage, computer failure or malfunction, or any and all
173
+ other commercial damages or losses), even if such Contributor
174
+ has been advised of the possibility of such damages.
175
+
176
+ 9. Accepting Warranty or Additional Liability. While redistributing
177
+ the Work or Derivative Works thereof, You may choose to offer,
178
+ and charge a fee for, acceptance of support, warranty, indemnity,
179
+ or other liability obligations and/or rights consistent with this
180
+ License. However, in accepting such obligations, You may act only
181
+ on Your own behalf and on Your sole responsibility, not on behalf
182
+ of any other Contributor, and only if You agree to indemnify,
183
+ defend, and hold each Contributor harmless for any liability
184
+ incurred by, or claims asserted against, such Contributor by reason
185
+ of your accepting any such warranty or additional liability.
186
+
187
+ END OF TERMS AND CONDITIONS
188
+
189
+ APPENDIX: How to apply the Apache License to your work.
190
+
191
+ To apply the Apache License to your work, attach the following
192
+ boilerplate notice, with the fields enclosed by brackets "{}"
193
+ replaced with your own identifying information. (Don't include
194
+ the brackets!) The text should be enclosed in the appropriate
195
+ comment syntax for the file format. We also recommend that a
196
+ file or class name and description of purpose be included on the
197
+ same "printed page" as the copyright notice for easier
198
+ identification within third-party archives.
199
+
200
+ Copyright 2023 Apify Technologies s.r.o.
201
+
202
+ Licensed under the Apache License, Version 2.0 (the "License");
203
+ you may not use this file except in compliance with the License.
204
+ You may obtain a copy of the License at
205
+
206
+ http://www.apache.org/licenses/LICENSE-2.0
207
+
208
+ Unless required by applicable law or agreed to in writing, software
209
+ distributed under the License is distributed on an "AS IS" BASIS,
210
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
211
+ See the License for the specific language governing permissions and
212
+ limitations under the License.
213
+ License-File: LICENSE
214
+ Keywords: apify,automation,chrome,crawlee,crawler,headless,scraper,scraping,sdk
215
+ Classifier: Development Status :: 5 - Production/Stable
216
+ Classifier: Intended Audience :: Developers
217
+ Classifier: License :: OSI Approved :: Apache Software License
218
+ Classifier: Operating System :: OS Independent
219
+ Classifier: Programming Language :: Python :: 3.9
220
+ Classifier: Programming Language :: Python :: 3.10
221
+ Classifier: Programming Language :: Python :: 3.11
222
+ Classifier: Programming Language :: Python :: 3.12
223
+ Classifier: Programming Language :: Python :: 3.13
224
+ Classifier: Topic :: Software Development :: Libraries
225
+ Requires-Python: >=3.9
226
+ Requires-Dist: apify-client>=1.9.2
227
+ Requires-Dist: apify-shared>=1.2.1
228
+ Requires-Dist: crawlee~=0.5.0
229
+ Requires-Dist: cryptography>=42.0.0
230
+ Requires-Dist: httpx>=0.27.0
231
+ Requires-Dist: lazy-object-proxy>=1.10.0
232
+ Requires-Dist: more-itertools>=10.2.0
233
+ Requires-Dist: typing-extensions>=4.1.0
234
+ Requires-Dist: websockets<14.0.0,>=10.0
235
+ Provides-Extra: scrapy
236
+ Requires-Dist: scrapy>=2.11.0; extra == 'scrapy'
237
+ Description-Content-Type: text/markdown
238
+
239
+ # Apify SDK for Python
240
+
241
+ The Apify SDK for Python is the official library to create [Apify Actors](https://docs.apify.com/platform/actors)
242
+ in Python. It provides useful features like Actor lifecycle management, local storage emulation, and Actor
243
+ event handling.
244
+
245
+ If you just need to access the [Apify API](https://docs.apify.com/api/v2) from your Python applications,
246
+ check out the [Apify Client for Python](https://docs.apify.com/api/client/python) instead.
247
+
248
+ ## Installation
249
+
250
+ The Apify SDK for Python is available on PyPI as the `apify` package.
251
+ For default installation, using Pip, run the following:
252
+
253
+ ```bash
254
+ pip install apify
255
+ ```
256
+
257
+ For users interested in integrating Apify with Scrapy, we provide a package extra called `scrapy`.
258
+ To install Apify with the `scrapy` extra, use the following command:
259
+
260
+ ```bash
261
+ pip install apify[scrapy]
262
+ ```
263
+
264
+ ## Documentation
265
+
266
+ For usage instructions, check the documentation on [Apify Docs](https://docs.apify.com/sdk/python/).
267
+
268
+ ## Examples
269
+
270
+ Below are few examples demonstrating how to use the Apify SDK with some web scraping-related libraries.
271
+
272
+ ### Apify SDK with HTTPX and BeautifulSoup
273
+
274
+ This example illustrates how to integrate the Apify SDK with [HTTPX](https://www.python-httpx.org/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) to scrape data from web pages.
275
+
276
+ ```python
277
+ from bs4 import BeautifulSoup
278
+ from httpx import AsyncClient
279
+
280
+ from apify import Actor
281
+
282
+
283
+ async def main() -> None:
284
+ async with Actor:
285
+ # Retrieve the Actor input, and use default values if not provided.
286
+ actor_input = await Actor.get_input() or {}
287
+ start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])
288
+
289
+ # Open the default request queue for handling URLs to be processed.
290
+ request_queue = await Actor.open_request_queue()
291
+
292
+ # Enqueue the start URLs.
293
+ for start_url in start_urls:
294
+ url = start_url.get('url')
295
+ await request_queue.add_request(url)
296
+
297
+ # Process the URLs from the request queue.
298
+ while request := await request_queue.fetch_next_request():
299
+ Actor.log.info(f'Scraping {request.url} ...')
300
+
301
+ # Fetch the HTTP response from the specified URL using HTTPX.
302
+ async with AsyncClient() as client:
303
+ response = await client.get(request.url)
304
+
305
+ # Parse the HTML content using Beautiful Soup.
306
+ soup = BeautifulSoup(response.content, 'html.parser')
307
+
308
+ # Extract the desired data.
309
+ data = {
310
+ 'url': actor_input['url'],
311
+ 'title': soup.title.string,
312
+ 'h1s': [h1.text for h1 in soup.find_all('h1')],
313
+ 'h2s': [h2.text for h2 in soup.find_all('h2')],
314
+ 'h3s': [h3.text for h3 in soup.find_all('h3')],
315
+ }
316
+
317
+ # Store the extracted data to the default dataset.
318
+ await Actor.push_data(data)
319
+ ```
320
+
321
+ ### Apify SDK with PlaywrightCrawler from Crawlee
322
+
323
+ This example demonstrates how to use the Apify SDK alongside `PlaywrightCrawler` from [Crawlee](https://crawlee.dev/python) to perform web scraping.
324
+
325
+ ```python
326
+ from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
327
+
328
+ from apify import Actor
329
+
330
+
331
+ async def main() -> None:
332
+ async with Actor:
333
+ # Retrieve the Actor input, and use default values if not provided.
334
+ actor_input = await Actor.get_input() or {}
335
+ start_urls = [url.get('url') for url in actor_input.get('start_urls', [{'url': 'https://apify.com'}])]
336
+
337
+ # Exit if no start URLs are provided.
338
+ if not start_urls:
339
+ Actor.log.info('No start URLs specified in Actor input, exiting...')
340
+ await Actor.exit()
341
+
342
+ # Create a crawler.
343
+ crawler = PlaywrightCrawler(
344
+ # Limit the crawl to max requests. Remove or increase it for crawling all links.
345
+ max_requests_per_crawl=50,
346
+ headless=True,
347
+ )
348
+
349
+ # Define a request handler, which will be called for every request.
350
+ @crawler.router.default_handler
351
+ async def request_handler(context: PlaywrightCrawlingContext) -> None:
352
+ url = context.request.url
353
+ Actor.log.info(f'Scraping {url}...')
354
+
355
+ # Extract the desired data.
356
+ data = {
357
+ 'url': context.request.url,
358
+ 'title': await context.page.title(),
359
+ 'h1s': [await h1.text_content() for h1 in await context.page.locator('h1').all()],
360
+ 'h2s': [await h2.text_content() for h2 in await context.page.locator('h2').all()],
361
+ 'h3s': [await h3.text_content() for h3 in await context.page.locator('h3').all()],
362
+ }
363
+
364
+ # Store the extracted data to the default dataset.
365
+ await context.push_data(data)
366
+
367
+ # Enqueue additional links found on the current page.
368
+ await context.enqueue_links()
369
+
370
+ # Run the crawler with the starting URLs.
371
+ await crawler.run(start_urls)
372
+ ```
373
+
374
+ ## What are Actors?
375
+
376
+ Actors are serverless cloud programs that can do almost anything a human can do in a web browser.
377
+ They can do anything from small tasks such as filling in forms or unsubscribing from online services,
378
+ all the way up to scraping and processing vast numbers of web pages.
379
+
380
+ They can be run either locally, or on the [Apify platform](https://docs.apify.com/platform/),
381
+ where you can run them at scale, monitor them, schedule them, or publish and monetize them.
382
+
383
+ If you're new to Apify, learn [what is Apify](https://docs.apify.com/platform/about)
384
+ in the Apify platform documentation.
385
+
386
+ ## Creating Actors
387
+
388
+ To create and run Actors through Apify Console,
389
+ see the [Console documentation](https://docs.apify.com/academy/getting-started/creating-actors#choose-your-template).
390
+
391
+ To create and run Python Actors locally, check the documentation for
392
+ [how to create and run Python Actors locally](https://docs.apify.com/sdk/python/docs/overview/running-locally).
393
+
394
+ ## Guides
395
+
396
+ To see how you can use the Apify SDK with other popular libraries used for web scraping,
397
+ check out our guides for using
398
+ [Requests and HTTPX](https://docs.apify.com/sdk/python/docs/guides/requests-and-httpx),
399
+ [Beautiful Soup](https://docs.apify.com/sdk/python/docs/guides/beautiful-soup),
400
+ [Playwright](https://docs.apify.com/sdk/python/docs/guides/playwright),
401
+ [Selenium](https://docs.apify.com/sdk/python/docs/guides/selenium),
402
+ or [Scrapy](https://docs.apify.com/sdk/python/docs/guides/scrapy).
403
+
404
+ ## Usage concepts
405
+
406
+ To learn more about the features of the Apify SDK and how to use them,
407
+ check out the Usage Concepts section in the sidebar,
408
+ particularly the guides for the [Actor lifecycle](https://docs.apify.com/sdk/python/docs/concepts/actor-lifecycle),
409
+ [working with storages](https://docs.apify.com/sdk/python/docs/concepts/storages),
410
+ [handling Actor events](https://docs.apify.com/sdk/python/docs/concepts/actor-events)
411
+ or [how to use proxies](https://docs.apify.com/sdk/python/docs/concepts/proxy-management).
@@ -1,12 +1,15 @@
1
1
  apify/__init__.py,sha256=HpgKg2FZWJuSPfDygzJ62psylhw4NN4tKFnoYUIhcd4,838
2
- apify/_actor.py,sha256=gZVbubkFFaNVcEoU_343Cmlc4Svtxd5x9J1WhWZcE4o,46507
3
- apify/_configuration.py,sha256=T3Z_o_W98iSyTbrutfb578yW51aexZ_V0FcLwTxFLjI,10878
2
+ apify/_actor.py,sha256=EB3gGjASV0PbPJ6BtgOq45HN23vM-9ceNCNRfeh2BkQ,48821
3
+ apify/_charging.py,sha256=m7hJIQde4M7vS4g_4hsNRP5xHNXjYQ8MyqOEGeNb7VY,12267
4
+ apify/_configuration.py,sha256=yidcWHsu-IJ2mmLmXStKq_HHcdfQxZq7koYjlZfRnQ8,11128
4
5
  apify/_consts.py,sha256=_Xq4hOfOA1iZ3n1P967YWdyncKivpbX6RTlp_qanUoE,330
5
6
  apify/_crypto.py,sha256=e0_aM3l9_5Osk-jszYOOjrAKK60OggSHbiw5c30QnsU,5638
6
- apify/_models.py,sha256=Btlz-23obKY5tJ75JnUwkVNC2lmU1IEBbdU3HvWaVhg,5748
7
+ apify/_models.py,sha256=-Y0rljBJWxMMCp8iDCTG4UV3bEvNZzp-kx2SYbPfeIY,7919
7
8
  apify/_platform_event_manager.py,sha256=44xyV0Lpzf4h4VZ0rkyYg_nhbQkEONNor8_Z9gIKO40,7899
8
9
  apify/_proxy_configuration.py,sha256=c-O6_PZ9pUD-i4J0RFEKTtfyJPP2rTRJJA1TH8NVsV8,13189
9
- apify/_utils.py,sha256=CCLkpAsZKp00ykm88Z_Fbck5PNT0j6mJYOuD0RxzZUs,1620
10
+ apify/_utils.py,sha256=92byxeXTpDFwhBq7ZS-obeXKtKWvVzCZMV0Drg3EjhQ,1634
11
+ apify/log.py,sha256=j-E4t-WeA93bc1NCQRG8sTntehQCiiN8ia-MdQe3_Ts,1291
12
+ apify/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
13
  apify/apify_storage_client/__init__.py,sha256=-UbR68bFsDR6ln8OFs4t50eqcnY36hujO-SeOt-KmcA,114
11
14
  apify/apify_storage_client/_apify_storage_client.py,sha256=jTX5vd-K9mnFTyZu2V2dUg7oyWogvmNIDUlEXnvIlOw,2766
12
15
  apify/apify_storage_client/_dataset_client.py,sha256=UUodnR_MQBg5RkURrfegkGJWR5OmdPPgPfGepvkdQoU,5580
@@ -16,26 +19,24 @@ apify/apify_storage_client/_key_value_store_collection_client.py,sha256=NxD-3XDJ
16
19
  apify/apify_storage_client/_request_queue_client.py,sha256=n-CR-hA5LM6_8IwiMwQ9tT2juavq7X2zC3ZNlrtv-2s,5156
17
20
  apify/apify_storage_client/_request_queue_collection_client.py,sha256=MdzgbQb2D8rHWpUlPCrQSHRlAi0fI0PSZ9bYagr-MhY,1571
18
21
  apify/apify_storage_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
- apify/log.py,sha256=j-E4t-WeA93bc1NCQRG8sTntehQCiiN8ia-MdQe3_Ts,1291
20
- apify/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
22
  apify/scrapy/__init__.py,sha256=m2a0ts_JY9xJkBy4JU5mV8PJqjA3GGKLXBFu4nl-n-A,1048
22
23
  apify/scrapy/_actor_runner.py,sha256=rXWSnlQWGskDUH8PtLCv5SkOIx4AiVa4QbCYeCett5c,938
23
24
  apify/scrapy/_async_thread.py,sha256=AfeH9ZkSRZXxL11wzwrroDNsTzq4tAvURlinUZBtYMA,4753
24
25
  apify/scrapy/_logging_config.py,sha256=hFq90fNtZyjjJA7w2k-mtuEC8xCFiBMTalbwPDcaig4,2022
26
+ apify/scrapy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ apify/scrapy/requests.py,sha256=tOiFtG0kyzbBwtmaOisLAcpJENR1eDtpPR1nRH7JJGg,6551
28
+ apify/scrapy/scheduler.py,sha256=-r1wZjMmeRDPxZKGHO-EYDYpGdDgSPAdNgMFViqUK8E,6019
29
+ apify/scrapy/utils.py,sha256=5cka33PWc_at14yjhnLkCvY4h-ySUgVVhhDLxTy39ZI,1965
25
30
  apify/scrapy/middlewares/__init__.py,sha256=tfW-d3WFWLeNEjL8fTmon6NwgD-OXx1Bw2fBdU-wPy4,114
26
31
  apify/scrapy/middlewares/apify_proxy.py,sha256=CDAOXS3bcVDZHM3B0GvhXbxEikMIadLF_0P73WL_nI4,5550
27
32
  apify/scrapy/middlewares/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
33
  apify/scrapy/pipelines/__init__.py,sha256=GWPeLN_Zwj8vRBWtXW6DaxdB7mvyQ7Jw5Tz1ccgWlZI,119
29
34
  apify/scrapy/pipelines/actor_dataset_push.py,sha256=XUUyznQTD-E3wYUUFt2WAOnWhbnRrY0WuedlfYfYhDI,846
30
35
  apify/scrapy/pipelines/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
- apify/scrapy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
- apify/scrapy/requests.py,sha256=tOiFtG0kyzbBwtmaOisLAcpJENR1eDtpPR1nRH7JJGg,6551
33
- apify/scrapy/scheduler.py,sha256=-r1wZjMmeRDPxZKGHO-EYDYpGdDgSPAdNgMFViqUK8E,6019
34
- apify/scrapy/utils.py,sha256=5cka33PWc_at14yjhnLkCvY4h-ySUgVVhhDLxTy39ZI,1965
35
36
  apify/storages/__init__.py,sha256=FW-z6ubuPnHGM-Wp15T8mR5q6lnpDGrCW-IkgZd5L30,177
36
37
  apify/storages/_request_list.py,sha256=-lZJcE5nq69aJhGFJ7Sh2ctqgAWUDyOwYm5_0y1hdAE,5865
37
38
  apify/storages/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
38
- apify-2.3.0b2.dist-info/LICENSE,sha256=AsFjHssKjj4LGd2ZCqXn6FBzMqcWdjQre1byPPSypVw,11355
39
- apify-2.3.0b2.dist-info/METADATA,sha256=I3msK8pLrpUgYlJOoHtXjHuaQKndb-ySirRp2c8f0ok,8696
40
- apify-2.3.0b2.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
41
- apify-2.3.0b2.dist-info/RECORD,,
39
+ apify-2.3.1b1.dist-info/METADATA,sha256=smwKRzXW6yc8qQBdfNzmI0UX0ixceooEkEsLsiHoM9k,21566
40
+ apify-2.3.1b1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
41
+ apify-2.3.1b1.dist-info/licenses/LICENSE,sha256=AsFjHssKjj4LGd2ZCqXn6FBzMqcWdjQre1byPPSypVw,11355
42
+ apify-2.3.1b1.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.0.1
2
+ Generator: hatchling 1.27.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,213 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: apify
3
- Version: 2.3.0b2
4
- Summary: Apify SDK for Python
5
- License: Apache-2.0
6
- Keywords: apify,sdk,automation,chrome,crawlee,crawler,headless,scraper,scraping
7
- Author: Apify Technologies s.r.o.
8
- Author-email: support@apify.com
9
- Requires-Python: >=3.9,<4.0
10
- Classifier: Development Status :: 5 - Production/Stable
11
- Classifier: Intended Audience :: Developers
12
- Classifier: License :: OSI Approved :: Apache Software License
13
- Classifier: Operating System :: OS Independent
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.9
16
- Classifier: Programming Language :: Python :: 3.10
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Topic :: Software Development :: Libraries
21
- Provides-Extra: scrapy
22
- Requires-Dist: apify-client (>=1.9.1)
23
- Requires-Dist: apify-shared (>=1.2.1)
24
- Requires-Dist: crawlee (>=0.5.1,<0.6.0)
25
- Requires-Dist: cryptography (>=42.0.0)
26
- Requires-Dist: httpx (>=0.27.0)
27
- Requires-Dist: lazy-object-proxy (>=1.10.0)
28
- Requires-Dist: more_itertools (>=10.2.0)
29
- Requires-Dist: scrapy (>=2.11.0) ; extra == "scrapy"
30
- Requires-Dist: typing-extensions (>=4.1.0)
31
- Requires-Dist: websockets (>=10.0,<14.0.0)
32
- Project-URL: Apify Homepage, https://apify.com
33
- Project-URL: Changelog, https://docs.apify.com/sdk/python/docs/changelog
34
- Project-URL: Documentation, https://docs.apify.com/sdk/python/
35
- Project-URL: Homepage, https://docs.apify.com/sdk/python/
36
- Project-URL: Issue Tracker, https://github.com/apify/apify-sdk-python/issues
37
- Project-URL: Repository, https://github.com/apify/apify-sdk-python
38
- Description-Content-Type: text/markdown
39
-
40
- # Apify SDK for Python
41
-
42
- The Apify SDK for Python is the official library to create [Apify Actors](https://docs.apify.com/platform/actors)
43
- in Python. It provides useful features like Actor lifecycle management, local storage emulation, and Actor
44
- event handling.
45
-
46
- If you just need to access the [Apify API](https://docs.apify.com/api/v2) from your Python applications,
47
- check out the [Apify Client for Python](https://docs.apify.com/api/client/python) instead.
48
-
49
- ## Installation
50
-
51
- The Apify SDK for Python is available on PyPI as the `apify` package.
52
- For default installation, using Pip, run the following:
53
-
54
- ```bash
55
- pip install apify
56
- ```
57
-
58
- For users interested in integrating Apify with Scrapy, we provide a package extra called `scrapy`.
59
- To install Apify with the `scrapy` extra, use the following command:
60
-
61
- ```bash
62
- pip install apify[scrapy]
63
- ```
64
-
65
- ## Documentation
66
-
67
- For usage instructions, check the documentation on [Apify Docs](https://docs.apify.com/sdk/python/).
68
-
69
- ## Examples
70
-
71
- Below are few examples demonstrating how to use the Apify SDK with some web scraping-related libraries.
72
-
73
- ### Apify SDK with HTTPX and BeautifulSoup
74
-
75
- This example illustrates how to integrate the Apify SDK with [HTTPX](https://www.python-httpx.org/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) to scrape data from web pages.
76
-
77
- ```python
78
- from bs4 import BeautifulSoup
79
- from httpx import AsyncClient
80
-
81
- from apify import Actor
82
-
83
-
84
- async def main() -> None:
85
- async with Actor:
86
- # Retrieve the Actor input, and use default values if not provided.
87
- actor_input = await Actor.get_input() or {}
88
- start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])
89
-
90
- # Open the default request queue for handling URLs to be processed.
91
- request_queue = await Actor.open_request_queue()
92
-
93
- # Enqueue the start URLs.
94
- for start_url in start_urls:
95
- url = start_url.get('url')
96
- await request_queue.add_request(url)
97
-
98
- # Process the URLs from the request queue.
99
- while request := await request_queue.fetch_next_request():
100
- Actor.log.info(f'Scraping {request.url} ...')
101
-
102
- # Fetch the HTTP response from the specified URL using HTTPX.
103
- async with AsyncClient() as client:
104
- response = await client.get(request.url)
105
-
106
- # Parse the HTML content using Beautiful Soup.
107
- soup = BeautifulSoup(response.content, 'html.parser')
108
-
109
- # Extract the desired data.
110
- data = {
111
- 'url': actor_input['url'],
112
- 'title': soup.title.string,
113
- 'h1s': [h1.text for h1 in soup.find_all('h1')],
114
- 'h2s': [h2.text for h2 in soup.find_all('h2')],
115
- 'h3s': [h3.text for h3 in soup.find_all('h3')],
116
- }
117
-
118
- # Store the extracted data to the default dataset.
119
- await Actor.push_data(data)
120
- ```
121
-
122
- ### Apify SDK with PlaywrightCrawler from Crawlee
123
-
124
- This example demonstrates how to use the Apify SDK alongside `PlaywrightCrawler` from [Crawlee](https://crawlee.dev/python) to perform web scraping.
125
-
126
- ```python
127
- from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
128
-
129
- from apify import Actor
130
-
131
-
132
- async def main() -> None:
133
- async with Actor:
134
- # Retrieve the Actor input, and use default values if not provided.
135
- actor_input = await Actor.get_input() or {}
136
- start_urls = [url.get('url') for url in actor_input.get('start_urls', [{'url': 'https://apify.com'}])]
137
-
138
- # Exit if no start URLs are provided.
139
- if not start_urls:
140
- Actor.log.info('No start URLs specified in Actor input, exiting...')
141
- await Actor.exit()
142
-
143
- # Create a crawler.
144
- crawler = PlaywrightCrawler(
145
- # Limit the crawl to max requests. Remove or increase it for crawling all links.
146
- max_requests_per_crawl=50,
147
- headless=True,
148
- )
149
-
150
- # Define a request handler, which will be called for every request.
151
- @crawler.router.default_handler
152
- async def request_handler(context: PlaywrightCrawlingContext) -> None:
153
- url = context.request.url
154
- Actor.log.info(f'Scraping {url}...')
155
-
156
- # Extract the desired data.
157
- data = {
158
- 'url': context.request.url,
159
- 'title': await context.page.title(),
160
- 'h1s': [await h1.text_content() for h1 in await context.page.locator('h1').all()],
161
- 'h2s': [await h2.text_content() for h2 in await context.page.locator('h2').all()],
162
- 'h3s': [await h3.text_content() for h3 in await context.page.locator('h3').all()],
163
- }
164
-
165
- # Store the extracted data to the default dataset.
166
- await context.push_data(data)
167
-
168
- # Enqueue additional links found on the current page.
169
- await context.enqueue_links()
170
-
171
- # Run the crawler with the starting URLs.
172
- await crawler.run(start_urls)
173
- ```
174
-
175
- ## What are Actors?
176
-
177
- Actors are serverless cloud programs that can do almost anything a human can do in a web browser.
178
- They can do anything from small tasks such as filling in forms or unsubscribing from online services,
179
- all the way up to scraping and processing vast numbers of web pages.
180
-
181
- They can be run either locally, or on the [Apify platform](https://docs.apify.com/platform/),
182
- where you can run them at scale, monitor them, schedule them, or publish and monetize them.
183
-
184
- If you're new to Apify, learn [what is Apify](https://docs.apify.com/platform/about)
185
- in the Apify platform documentation.
186
-
187
- ## Creating Actors
188
-
189
- To create and run Actors through Apify Console,
190
- see the [Console documentation](https://docs.apify.com/academy/getting-started/creating-actors#choose-your-template).
191
-
192
- To create and run Python Actors locally, check the documentation for
193
- [how to create and run Python Actors locally](https://docs.apify.com/sdk/python/docs/overview/running-locally).
194
-
195
- ## Guides
196
-
197
- To see how you can use the Apify SDK with other popular libraries used for web scraping,
198
- check out our guides for using
199
- [Requests and HTTPX](https://docs.apify.com/sdk/python/docs/guides/requests-and-httpx),
200
- [Beautiful Soup](https://docs.apify.com/sdk/python/docs/guides/beautiful-soup),
201
- [Playwright](https://docs.apify.com/sdk/python/docs/guides/playwright),
202
- [Selenium](https://docs.apify.com/sdk/python/docs/guides/selenium),
203
- or [Scrapy](https://docs.apify.com/sdk/python/docs/guides/scrapy).
204
-
205
- ## Usage concepts
206
-
207
- To learn more about the features of the Apify SDK and how to use them,
208
- check out the Usage Concepts section in the sidebar,
209
- particularly the guides for the [Actor lifecycle](https://docs.apify.com/sdk/python/docs/concepts/actor-lifecycle),
210
- [working with storages](https://docs.apify.com/sdk/python/docs/concepts/storages),
211
- [handling Actor events](https://docs.apify.com/sdk/python/docs/concepts/actor-events)
212
- or [how to use proxies](https://docs.apify.com/sdk/python/docs/concepts/proxy-management).
213
-