scrapely-python 0.1.41__tar.gz → 0.1.42__tar.gz

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.
Files changed (84) hide show
  1. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/CHANGELOG.md +17 -0
  2. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/PKG-INFO +1 -1
  3. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/pyproject.toml +1 -1
  4. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_client.py +71 -15
  5. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/solver.py +364 -0
  6. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  7. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/LICENSE +0 -0
  8. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/LICENSE-APACHE +0 -0
  9. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/MANIFEST.in +0 -0
  10. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/NOTICE +0 -0
  11. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/README.md +0 -0
  12. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/setup.cfg +0 -0
  13. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/__init__.py +0 -0
  14. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/_browser_locations.py +0 -0
  15. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/actor.py +0 -0
  16. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/browser_configuration.py +0 -0
  17. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/cdp_retry.py +0 -0
  18. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/charging.py +0 -0
  19. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/charging_client.py +0 -0
  20. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/configuration.py +0 -0
  21. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/crypto/__init__.py +0 -0
  22. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/crypto/_secrets.py +0 -0
  23. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/errors.py +0 -0
  24. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/events/__init__.py +0 -0
  25. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/events/_types.py +0 -0
  26. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/events/event_manager.py +0 -0
  27. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/__init__.py +0 -0
  28. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_capture.py +0 -0
  29. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_compat.py +0 -0
  30. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_detect.py +0 -0
  31. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_headers.py +0 -0
  32. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_options.py +0 -0
  33. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_policy.py +0 -0
  34. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_profiles.py +0 -0
  35. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_response.py +0 -0
  36. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_stats.py +0 -0
  37. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/_transport.py +0 -0
  38. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/http/profiles.json +0 -0
  39. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/log.py +0 -0
  40. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/patch_browser_pool.py +0 -0
  41. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/pricing_types.py +0 -0
  42. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/proxy_configuration.py +0 -0
  43. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/py.typed +0 -0
  44. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/request_loaders/__init__.py +0 -0
  45. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  46. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/__init__.py +0 -0
  47. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/_actor_runner.py +0 -0
  48. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/_async_thread.py +0 -0
  49. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/_logging_config.py +0 -0
  50. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/_serialization.py +0 -0
  51. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/_warnings.py +0 -0
  52. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  53. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  54. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  55. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  56. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  57. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  58. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  59. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/requests.py +0 -0
  60. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/scheduler.py +0 -0
  61. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/scrapy/utils.py +0 -0
  62. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/__init__.py +0 -0
  63. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/_file_system/__init__.py +0 -0
  64. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  65. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  66. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/_metadata.py +0 -0
  67. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/api_client.py +0 -0
  68. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/client.py +0 -0
  69. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/patch_storage.py +0 -0
  70. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  71. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  72. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  73. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  74. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  75. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/types.py +0 -0
  76. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage/utils.py +0 -0
  77. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storage_clients/__init__.py +0 -0
  78. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/storages/__init__.py +0 -0
  79. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/types.py +0 -0
  80. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely/webhook.py +0 -0
  81. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely_python.egg-info/SOURCES.txt +0 -0
  82. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  83. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely_python.egg-info/requires.txt +0 -0
  84. {scrapely_python-0.1.41 → scrapely_python-0.1.42}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.42] - 2026-11-02
8
+
9
+ - **Sessions that keep their identity: `http.session(keep_identity=True)`.** A pinned `scrapely.http` session used to retire its identity on the first block (a 403, a challenge page, a network error). The session then moved to a new exit, a new profile and an empty cookie jar. That breaks every challenge solve: the challenge page, the solver's script and submission requests and the page fetched again must all share one identity. With `keep_identity=True`:
10
+ - a block comes back to the caller (`response.blocked` names it) and an error is raised, with no rotation;
11
+ - the next request goes out on the same profile, exit and jar, with the cookies the block set;
12
+ - `max_usage` / `max_age` do not retire it;
13
+ - `session.rotate()` moves the session to a fresh identity when you decide to.
14
+
15
+ The default (`keep_identity=False`) is unchanged. The option is available on `AsyncClient.session()` and `Client.session()`.
16
+ - **`scrapely.solver.AkamaiSensor`: Akamai Bot Manager on your own session, the way the solver provider's examples do it.**
17
+ - `solve_sbsd(session, url, html)` handles a page that loads an SBSD bundle. It fetches the bundle on your session, gets the ledger from the solver (`/akamai/sbsd/generate-session`), then POSTs the ledger rows to the bundle path on your session.
18
+ - `solve_abck(session, url, html)` runs the `_abck` sensor over the solver's WebSocket session (`/akamai/session`, which the platform relays for runs). The solver generates each sensor; it is POSTed on your session with your client's own headers, and rounds continue until `_abck` is accepted (`~0~`).
19
+ - `solve()` does SBSD when the page carries a bundle, then `_abck`.
20
+
21
+ Use it with a `keep_identity=True` session (or one curl_cffi or httpx client), and set `profile_id` to the browser your client claims, e.g. `chrome-154-macos` for scrapely.http Chrome 154 on macOS. Submissions outside the target site are refused, and a refused session raises the platform's code (`VendorUnavailable`, `SolverRateLimited`, ...). Also new: `find_sensor_script()`, `find_sbsd_bundle()`, `abck_state()`, `SensorResult`.
22
+ - **`AkamaiSensor.solve_pixel(session, url, html)`: Akamai's third channel, the pixel collector.** A page that loads `/akam/<n>/<hex>` (often next to an inline `bazadebezolkohpepadr=` value) expects that script to POST to `/akam/<n>/pixel_<hex>`. The collector is fetched on your session, the solver writes the POST the collector would send (`/akamai/pixel/generate`), and it is POSTed to the collector's own endpoint on your session. Also new: `find_pixel_collector()`, `pixel_target()`.
23
+
7
24
  ## [0.1.41] - 2026-10-29
8
25
 
9
26
  - **A refused charge names the limit that refused it.** When a charge is refused or cut short, the platform now says why (HTTP 402 `error.reason`, and `limitedBy` on a partial acceptance): the run's item limit (`maxItems`), its maximum total charge (`maxTotalChargeUsd`) or the account balance. The SDK used to call all of them the spending limit; a run stopped by its item limit logged "The spending limit of this run (maxTotalChargeUsd = $3.0) has been reached". Now:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.41
3
+ Version: 0.1.42
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <hello@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scrapely-python"
7
- version = "0.1.41"
7
+ version = "0.1.42"
8
8
  description = "Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform"
9
9
  readme = "README.md"
10
10
  license = "MIT AND Apache-2.0"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import dataclasses
6
7
  import logging
7
8
  import random
8
9
  import threading
@@ -102,14 +103,30 @@ def _proxy_from_proxies(proxies: Any) -> Optional[str]:
102
103
 
103
104
 
104
105
  class _Pin:
105
- """Holder of a pinned identity (a session)."""
106
+ """Holder of a pinned identity (a session).
106
107
 
107
- __slots__ = ('identity', 'alock', 'tlock')
108
+ ``keep``: the identity is never retired or swapped by the client (no
109
+ rotation on a block or error, no usage/age expiry); only ``rotate()`` or
110
+ closing the session moves it to a new one.
111
+ """
112
+
113
+ __slots__ = ('identity', 'alock', 'tlock', 'keep')
108
114
 
109
- def __init__(self) -> None:
115
+ def __init__(self, keep: bool = False) -> None:
110
116
  self.identity: Optional[Identity] = None
111
117
  self.alock: Optional[asyncio.Lock] = None
112
118
  self.tlock = threading.Lock()
119
+ self.keep = keep
120
+
121
+
122
+ def _no_rotation(decision: Any) -> Any:
123
+ """The policy's decision with the rotation taken out (kept identities): stop here, retire nothing."""
124
+ try:
125
+ return dataclasses.replace(decision, retry=False, retire=False, delay=0.0)
126
+ except TypeError:
127
+ decision.retry = False
128
+ decision.retire = False
129
+ return decision
113
130
 
114
131
 
115
132
  class CookieStore:
@@ -522,7 +539,7 @@ class AsyncClient(_Base):
522
539
  pin.alock = asyncio.Lock()
523
540
  async with pin.alock:
524
541
  ident = pin.identity
525
- if ident is not None and ident.expired(self._clock(), self.max_usage, self.max_age):
542
+ if ident is not None and not pin.keep and ident.expired(self._clock(), self.max_usage, self.max_age):
526
543
  pin.identity = None
527
544
  await self._retire(ident)
528
545
  ident = None
@@ -558,6 +575,8 @@ class AsyncClient(_Base):
558
575
  async def _release(self, pin: Optional[_Pin], ident: Identity, retire: bool) -> None:
559
576
  ident.in_flight -= 1
560
577
  if pin is not None:
578
+ if pin.keep and pin.identity is ident:
579
+ return
561
580
  if retire or not self.sticky:
562
581
  if pin.identity is ident:
563
582
  pin.identity = None
@@ -658,12 +677,16 @@ class AsyncClient(_Base):
658
677
  # Cancelled or failed in our own code: nothing says the identity is burnt.
659
678
  await self._release(_pin, ident, retire=False)
660
679
  raise
680
+ if decision.retry and not decision.same_identity and _pin is not None and _pin.keep:
681
+ # A kept identity is never swapped: the block or error goes back to the caller as is.
682
+ decision = _no_rotation(decision)
661
683
  if not decision.retry:
662
684
  await self._release(_pin, ident, retire=decision.retire)
663
685
  ok = resp is not None and reason is None and resp.status_code < 500
664
686
  self._stats.record_request(ok)
665
687
  if resp is None:
666
- assert error is not None
688
+ if error is None:
689
+ raise RuntimeError('scrapely.http: request ended with no response and no error')
667
690
  raise error
668
691
  resp.blocked = reason
669
692
  return resp
@@ -703,14 +726,21 @@ class AsyncClient(_Base):
703
726
  async def options(self, url: str, **kwargs: Any) -> Response:
704
727
  return await self.request('OPTIONS', url, **kwargs)
705
728
 
706
- def session(self) -> 'AsyncHttpSession':
729
+ def session(self, keep_identity: bool = False) -> 'AsyncHttpSession':
707
730
  """A pinned identity for multi-step flows (homepage → API with its cookies).
708
731
 
709
732
  All requests of the session use one profile, proxy session and cookie
710
733
  jar. On a block the whole identity is retired and the session continues
711
734
  on a fresh one (new IP, new profile, empty jar).
735
+
736
+ ``keep_identity=True`` keeps the identity and its jar on a block or an
737
+ error too: the blocked response comes back (``response.blocked`` names
738
+ the block) and the next request goes out on the same profile, exit and
739
+ cookies. That is what a challenge solve needs (the SBSD bundle, the
740
+ sensor submissions and the page fetches must share one identity).
741
+ ``rotate()`` moves the session to a fresh identity when you decide to.
712
742
  """
713
- return AsyncHttpSession(self)
743
+ return AsyncHttpSession(self, keep_identity=keep_identity)
714
744
 
715
745
  async def aclose(self) -> None:
716
746
  if self._closed:
@@ -733,11 +763,21 @@ class AsyncClient(_Base):
733
763
  class AsyncHttpSession:
734
764
  """A pinned identity on an ``AsyncClient`` (see ``AsyncClient.session()``)."""
735
765
 
736
- def __init__(self, client: AsyncClient) -> None:
766
+ def __init__(self, client: AsyncClient, keep_identity: bool = False) -> None:
737
767
  self._client = client
738
- self._pin = _Pin()
768
+ self._pin = _Pin(keep=keep_identity)
739
769
  self.cookies = _SessionCookies(self)
740
770
 
771
+ @property
772
+ def keep_identity(self) -> bool:
773
+ return self._pin.keep
774
+
775
+ async def rotate(self) -> None:
776
+ """Retire the current identity; the next request opens a fresh one (new exit, profile and jar)."""
777
+ if self._pin.identity is not None:
778
+ ident, self._pin.identity = self._pin.identity, None
779
+ await self._client._retire(ident, force=ident.in_flight <= 0)
780
+
741
781
  @property
742
782
  def profile(self) -> Optional[str]:
743
783
  return self._pin.identity.profile.label if self._pin.identity else None
@@ -873,7 +913,7 @@ class Client(_Base):
873
913
  if pin is not None:
874
914
  with pin.tlock:
875
915
  ident = pin.identity
876
- if ident is not None and ident.expired(self._clock(), self.max_usage, self.max_age):
916
+ if ident is not None and not pin.keep and ident.expired(self._clock(), self.max_usage, self.max_age):
877
917
  pin.identity = None
878
918
  self._retire(ident)
879
919
  ident = None
@@ -918,6 +958,8 @@ class Client(_Base):
918
958
  with self._lock:
919
959
  ident.in_flight -= 1
920
960
  if pin is not None:
961
+ if pin.keep and pin.identity is ident:
962
+ return
921
963
  if retire or not self.sticky:
922
964
  with pin.tlock:
923
965
  if pin.identity is ident:
@@ -1023,12 +1065,15 @@ class Client(_Base):
1023
1065
  # Failed in our own code: nothing says the identity is burnt.
1024
1066
  self._release(_pin, ident, retire=False)
1025
1067
  raise
1068
+ if decision.retry and not decision.same_identity and _pin is not None and _pin.keep:
1069
+ decision = _no_rotation(decision)
1026
1070
  if not decision.retry:
1027
1071
  self._release(_pin, ident, retire=decision.retire)
1028
1072
  ok = resp is not None and reason is None and resp.status_code < 500
1029
1073
  self._stats.record_request(ok)
1030
1074
  if resp is None:
1031
- assert error is not None
1075
+ if error is None:
1076
+ raise RuntimeError('scrapely.http: request ended with no response and no error')
1032
1077
  raise error
1033
1078
  resp.blocked = reason
1034
1079
  return resp
@@ -1067,9 +1112,9 @@ class Client(_Base):
1067
1112
  def options(self, url: str, **kwargs: Any) -> Response:
1068
1113
  return self.request('OPTIONS', url, **kwargs)
1069
1114
 
1070
- def session(self) -> 'HttpSession':
1115
+ def session(self, keep_identity: bool = False) -> 'HttpSession':
1071
1116
  """A pinned identity for multi-step flows (see ``AsyncClient.session``)."""
1072
- return HttpSession(self)
1117
+ return HttpSession(self, keep_identity=keep_identity)
1073
1118
 
1074
1119
  def close(self) -> None:
1075
1120
  if self._closed:
@@ -1090,11 +1135,22 @@ class Client(_Base):
1090
1135
  class HttpSession:
1091
1136
  """A pinned identity on a sync ``Client`` (see ``Client.session()``)."""
1092
1137
 
1093
- def __init__(self, client: Client) -> None:
1138
+ def __init__(self, client: Client, keep_identity: bool = False) -> None:
1094
1139
  self._client = client
1095
- self._pin = _Pin()
1140
+ self._pin = _Pin(keep=keep_identity)
1096
1141
  self.cookies = _SessionCookies(self)
1097
1142
 
1143
+ @property
1144
+ def keep_identity(self) -> bool:
1145
+ return self._pin.keep
1146
+
1147
+ def rotate(self) -> None:
1148
+ """Retire the current identity; the next request opens a fresh one (new exit, profile and jar)."""
1149
+ with self._pin.tlock:
1150
+ ident, self._pin.identity = self._pin.identity, None
1151
+ if ident is not None:
1152
+ self._client._retire(ident, force=ident.in_flight <= 0)
1153
+
1098
1154
  @property
1099
1155
  def profile(self) -> Optional[str]:
1100
1156
  return self._pin.identity.profile.label if self._pin.identity else None
@@ -62,6 +62,7 @@ from typing import Any, Awaitable, Callable, Optional
62
62
  import httpx
63
63
 
64
64
  __all__ = [
65
+ "AkamaiSensor",
65
66
  "Clearance",
66
67
  "DEGRADED_STATUS_MESSAGE",
67
68
  "IpBanned",
@@ -72,11 +73,16 @@ __all__ = [
72
73
  "SolverAuthError",
73
74
  "SolverRateLimited",
74
75
  "SolverRequestInvalid",
76
+ "SensorResult",
75
77
  "SolverUnavailable",
76
78
  "VendorUnavailable",
79
+ "abck_state",
77
80
  "check_solver_response",
78
81
  "degraded_status_message",
79
82
  "detect_vendor",
83
+ "find_pixel_collector",
84
+ "find_sbsd_bundle",
85
+ "find_sensor_script",
80
86
  "is_blocked",
81
87
  "solver_env",
82
88
  "solver_status",
@@ -874,3 +880,361 @@ class Solver:
874
880
  if not ok:
875
881
  raise SolveAttemptError("still blocked after the clearance was applied")
876
882
  return clearance
883
+
884
+
885
+ # ─── Akamai Bot Manager on your own session (sensor WebSocket lane + SBSD) ──
886
+
887
+
888
+ _SCRIPT_SRC_RE = re.compile(r"<script[^>]+src=[\"']([^\"']+)[\"']", re.I)
889
+ _SBSD_NONCE_RE = re.compile(r"(?:^|&)v=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:&|$)", re.I)
890
+ _PIXEL_PATH_RE = re.compile(r"^/akam/\d+/")
891
+ _LONG_PATH_RE = re.compile(r"<script[^>]+src=[\"']((?:/[a-zA-Z0-9\-_]+){5,10}(?:\?v=[^\"']*)?)[\"']", re.I)
892
+ _AKAM_PIXEL_TAG_RE = re.compile(r"akam/13.*?top:\s?-999px.*?src=\"(.*?)\"", re.S)
893
+ _AKAM_KEYWORD_RE = re.compile(r"<script[^>]+src=[\"']([^\"']*/(?:akam|_abck|bm-)[^\"']+)[\"']", re.I)
894
+ _STRIP_SCRIPTS_RE = re.compile(r"<script\b[^<]*(?:(?!</script>)<[^<]*)*</script>", re.I)
895
+ # Headers the submission must carry from YOUR client (its fingerprint), never the solver's copy.
896
+ _OWN_HEADERS = {"user-agent", "cookie", "host", "content-length", "accept-language", "accept-encoding", "connection",
897
+ "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform"}
898
+
899
+
900
+ def _urljoin(base: str, ref: str) -> str:
901
+ from urllib.parse import urljoin
902
+
903
+ return urljoin(base, ref)
904
+
905
+
906
+ def _is_sbsd_bundle(url: str) -> bool:
907
+ u = httpx.URL(url)
908
+ return u.path.startswith("/.well-known/sbsd") or bool(_SBSD_NONCE_RE.search(u.query.decode() if isinstance(u.query, bytes) else str(u.query or "")))
909
+
910
+
911
+ def _is_sensor_candidate(url: str) -> bool:
912
+ return not _is_sbsd_bundle(url) and not _PIXEL_PATH_RE.match(httpx.URL(url).path)
913
+
914
+
915
+ def _sbsd_src(html: str, base_url: str) -> tuple[str, str] | None:
916
+ for m in _SCRIPT_SRC_RE.finditer(html or ""):
917
+ u = _urljoin(base_url, m.group(1))
918
+ if _is_sbsd_bundle(u):
919
+ return m.group(1), u
920
+ return None
921
+
922
+
923
+ def find_sbsd_bundle(html: str, base_url: str) -> str | None:
924
+ """URL of the SBSD bundle script a page loads (``src`` with a UUID ``v=``, or ``/.well-known/sbsd``), or None."""
925
+ found = _sbsd_src(html, base_url)
926
+ return found[1] if found else None
927
+
928
+
929
+ def find_sensor_script(html: str, base_url: str) -> str | None:
930
+ """URL of the Akamai ``_abck`` sensor script in a page, or None (the provider examples' three patterns)."""
931
+ html = html or ""
932
+ m = _AKAM_PIXEL_TAG_RE.search(html)
933
+ if m:
934
+ u = _urljoin(base_url, m.group(1))
935
+ if _is_sensor_candidate(u):
936
+ return u
937
+ for m in _LONG_PATH_RE.finditer(html):
938
+ u = _urljoin(base_url, m.group(1))
939
+ if _is_sensor_candidate(u):
940
+ return u
941
+ m = _AKAM_KEYWORD_RE.search(html)
942
+ if m:
943
+ u = _urljoin(base_url, m.group(1))
944
+ if _is_sensor_candidate(u):
945
+ return u
946
+ return None
947
+
948
+
949
+ _PIXEL_COLLECTOR_RE = re.compile(r"<script[^>]+src=[\"']([^\"']*/akam/\d+/[0-9a-f]{6,})[\"']", re.I)
950
+
951
+
952
+ def find_pixel_collector(html: str, base_url: str) -> str | None:
953
+ """URL of Akamai's pixel collector script (``/akam/<n>/<hex>``, it POSTs to ``/akam/<n>/pixel_<hex>``), or None."""
954
+ m = _PIXEL_COLLECTOR_RE.search(html or "")
955
+ return _urljoin(base_url, m.group(1)) if m else None
956
+
957
+
958
+ def pixel_target(collector_url: str) -> str:
959
+ """The endpoint a pixel collector POSTs to: its own directory, ``pixel_`` + its basename, no query."""
960
+ u = httpx.URL(collector_url)
961
+ head, _, name = u.path.rpartition("/")
962
+ return f"{u.scheme}://{u.host}{head}/pixel_{name}"
963
+
964
+
965
+ def abck_state(value: str | None) -> str | None:
966
+ """The state field of an ``_abck`` cookie: ``'0'`` accepted, ``'-1'`` keep going, None when absent."""
967
+ parts = (value or "").split("~")
968
+ return parts[1] if len(parts) > 1 else None
969
+
970
+
971
+ def _cookie_dict(session: Any) -> dict[str, str]:
972
+ jar = getattr(session, "cookies", None)
973
+ if jar is None:
974
+ return {}
975
+ try:
976
+ if hasattr(jar, "jar"):
977
+ return {c.name: c.value for c in jar.jar}
978
+ return dict(jar.items())
979
+ except Exception: # noqa: BLE001
980
+ return {}
981
+
982
+
983
+ def _ws_connect(url: str, headers: dict[str, str]) -> Any:
984
+ """websockets.connect with request headers (``additional_headers`` from 13, ``extra_headers`` before)."""
985
+ import websockets
986
+
987
+ try:
988
+ return websockets.connect(url, additional_headers=headers, max_size=32 * 1024 * 1024, open_timeout=30)
989
+ except TypeError:
990
+ return websockets.connect(url, extra_headers=headers, max_size=32 * 1024 * 1024, open_timeout=30)
991
+
992
+
993
+ def _refused_upgrade(exc: BaseException) -> tuple[int, str, str | None]:
994
+ """(status, body, Retry-After) of a refused WebSocket upgrade, across websockets versions."""
995
+ response = getattr(exc, "response", None)
996
+ if response is not None:
997
+ status = int(getattr(response, "status_code", 0) or 0)
998
+ raw = getattr(response, "body", b"") or b""
999
+ headers = getattr(response, "headers", None)
1000
+ return status, raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else str(raw), headers.get("retry-after") if headers is not None else None
1001
+ status = int(getattr(exc, "status_code", 0) or 0)
1002
+ headers = getattr(exc, "headers", None)
1003
+ return status, "", headers.get("retry-after") if headers is not None else None
1004
+
1005
+
1006
+ def _is_scrapely_http(session: Any) -> bool:
1007
+ return type(session).__module__.startswith("scrapely.http")
1008
+
1009
+
1010
+ async def _session_send(session: Any, method: str, url: str, *, headers: dict, body: str | bytes | None, kind: str, timeout: float) -> tuple[int, str]:
1011
+ kwargs: dict[str, Any] = {"headers": headers, "timeout": timeout}
1012
+ if body is not None:
1013
+ data = body.encode() if isinstance(body, str) else body
1014
+ kwargs["content" if (_is_httpx(session) or _is_scrapely_http(session)) else "data"] = data
1015
+ if _is_scrapely_http(session):
1016
+ # One identity for the whole solve: no rotation, and a 403 is an answer, not a block to route around.
1017
+ kwargs.update(kind=kind, max_rotations=0, is_blocked=lambda r: None)
1018
+ r = await session.request(method, url, **kwargs)
1019
+ return _status_body(r)
1020
+
1021
+
1022
+ @dataclass
1023
+ class SensorResult:
1024
+ """Outcome of ``AkamaiSensor.solve_abck``: whether the provider reported ``_abck`` accepted."""
1025
+
1026
+ accepted: bool
1027
+ rounds: int = 0
1028
+ submissions: int = 0
1029
+ abck: str | None = None
1030
+ error: str | None = None
1031
+
1032
+
1033
+ class AkamaiSensor:
1034
+ """Akamai Bot Manager solved on YOUR HTTP session, the way the provider's own examples do it.
1035
+
1036
+ Two independent channels, both answered through the session you pass, so
1037
+ every request carries your client's fingerprint, exit IP and cookie jar:
1038
+
1039
+ * ``solve_sbsd(session, url, html)``: the page loads an SBSD bundle (a
1040
+ script whose ``src`` has a UUID ``v=``, often a ~440-byte "Access Denied"
1041
+ bootstrap). The bundle is fetched on your session, the provider computes
1042
+ the ledger (``/akamai/sbsd/generate-session``), and its rows are POSTed to
1043
+ the bundle path on your session.
1044
+ * ``solve_abck(session, url, html)``: the classic ``_abck`` sensor over the
1045
+ provider's stateful WebSocket (``/akamai/session``, relayed by the
1046
+ platform for runs). The provider generates each sensor; it is POSTed on
1047
+ your session; rounds continue until ``_abck`` is ``~0~``.
1048
+
1049
+ ``solve(session, url, html)`` does SBSD when the page carries a bundle, then ``_abck``.
1050
+
1051
+ Use a session that keeps its identity on a block (``http.session(keep_identity=True)``
1052
+ of ``scrapely.http``, or one curl_cffi / httpx client): the solve, the
1053
+ retries and the page fetches must share one identity, jar and exit. The
1054
+ ``profile_id`` must be the browser your client claims (``chrome-154-macos``
1055
+ for scrapely.http Chrome 154 on macOS, ``chrome-146-macos`` for curl_cffi
1056
+ ``impersonate="chrome146"``); a mismatch shows as ``_abck`` stuck at ``~-1~``.
1057
+
1058
+ Example::
1059
+
1060
+ http = AsyncClient(proxy_configuration=proxy, fingerprint_options=FingerprintOptions(
1061
+ browsers=[{"name": "chrome", "min_version": 154, "max_version": 154}], operating_systems=["macos"]))
1062
+ session = http.session(keep_identity=True)
1063
+ akamai = AkamaiSensor(profile_id="chrome-154-macos")
1064
+ home = await session.get("https://www.example.com/")
1065
+ result = await akamai.solve(session, "https://www.example.com/", home.text)
1066
+ page = await session.get("https://www.example.com/item/1")
1067
+ """
1068
+
1069
+ def __init__(
1070
+ self,
1071
+ profile_id: str = "chrome-154-macos",
1072
+ *,
1073
+ telemetry: dict | None = None,
1074
+ timeout: float = 90.0,
1075
+ request_timeout: float = 30.0,
1076
+ max_rounds: int = 12,
1077
+ ) -> None:
1078
+ self.profile_id = profile_id
1079
+ self.telemetry = telemetry
1080
+ self.timeout = timeout
1081
+ self.request_timeout = request_timeout
1082
+ self.max_rounds = max_rounds
1083
+ self.sessions = 0
1084
+ self.accepted = 0
1085
+
1086
+ @staticmethod
1087
+ def _endpoint() -> tuple[str, str]:
1088
+ env = solver_env()
1089
+ if env is None:
1090
+ raise VendorUnavailable("solver_not_enabled", "akamai", None, "the platform solver is not available to this run")
1091
+ return env
1092
+
1093
+ # -- SBSD --------------------------------------------------------------------
1094
+
1095
+ async def solve_sbsd(self, session: Any, url: str, html: str) -> bool:
1096
+ """Answers the SBSD bundle of `html` (the page `url` as your session got it). False when there is none."""
1097
+ found = _sbsd_src(html, url)
1098
+ if not found:
1099
+ return False
1100
+ src_attr, bundle_url = found
1101
+ base, key = self._endpoint()
1102
+ origin = f"{httpx.URL(url).scheme}://{httpx.URL(url).host}"
1103
+ _, source = await _session_send(session, "GET", bundle_url, headers={"referer": url, "sec-fetch-dest": "script", "sec-fetch-mode": "no-cors", "sec-fetch-site": "same-origin", "accept": "*/*"}, body=None, kind="xhr", timeout=self.request_timeout)
1104
+ cookie_header = "; ".join(f"{k}={v}" for k, v in _cookie_dict(session).items())
1105
+ async with httpx.AsyncClient(timeout=self.timeout) as api:
1106
+ r = await api.post(
1107
+ f"{base}/akamai/sbsd/generate-session",
1108
+ headers={"x-api-key": key},
1109
+ json={"bundle": {"scriptSrc": src_attr, "source": source}, "document": {"url": url, "html": html, "cookieHeader": cookie_header}, "profile": {"id": self.profile_id}},
1110
+ )
1111
+ check_solver_response(r.status_code, r.text, r.headers.get("retry-after"))
1112
+ data = _json(r.text)
1113
+ rows = sorted([s for s in data.get("submissions") or [] if isinstance(s, dict) and s.get("resolvedUrl")], key=lambda s: s.get("index", 0))
1114
+ if not rows:
1115
+ raise SolveAttemptError(f"the SBSD ledger had no rows ({str(data.get('error') or data.get('outcome') or 'no reason')[:120]})")
1116
+ for row in rows:
1117
+ target = _urljoin(url, row["resolvedUrl"])
1118
+ if not _step_allowed(target, url):
1119
+ raise SolveAttemptError("the SBSD ledger pointed outside the target site; refused")
1120
+ await _session_send(session, "POST", target, headers={"content-type": "text/plain;charset=UTF-8", "origin": origin, "referer": url, "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*"}, body=row.get("body") or "", kind="xhr", timeout=self.request_timeout)
1121
+ return True
1122
+
1123
+ # -- pixel channel (/akam/<n>/<hex> collector) -----------------------------------
1124
+
1125
+ async def solve_pixel(self, session: Any, url: str, html: str) -> bool:
1126
+ """Answers Akamai's pixel channel of `html`: the collector script is fetched on your session, the solver
1127
+ writes the POST the collector would send (``/akamai/pixel/generate``), and it is POSTed to the collector's
1128
+ ``pixel_`` endpoint on your session. False when the page has no collector."""
1129
+ collector = find_pixel_collector(html, url)
1130
+ if not collector:
1131
+ return False
1132
+ base, key = self._endpoint()
1133
+ origin = f"{httpx.URL(url).scheme}://{httpx.URL(url).host}"
1134
+ _, source = await _session_send(session, "GET", collector, headers={"referer": url, "sec-fetch-dest": "script", "sec-fetch-mode": "no-cors", "sec-fetch-site": "same-origin", "accept": "*/*"}, body=None, kind="xhr", timeout=self.request_timeout)
1135
+ cookie_header = "; ".join(f"{k}={v}" for k, v in _cookie_dict(session).items())
1136
+ async with httpx.AsyncClient(timeout=self.timeout) as api:
1137
+ r = await api.post(
1138
+ f"{base}/akamai/pixel/generate",
1139
+ headers={"x-api-key": key, "accept": "application/json"},
1140
+ json={"document": {"url": url, "html": html, **({"cookieHeader": cookie_header} if cookie_header else {})},
1141
+ "profile": {"id": self.profile_id}, "script": {"source": source, "url": collector}},
1142
+ )
1143
+ check_solver_response(r.status_code, r.text, r.headers.get("retry-after"))
1144
+ data = _json(r.text)
1145
+ request = data.get("request") if isinstance(data.get("request"), dict) else {}
1146
+ if not data.get("ok") or not isinstance(request.get("body"), str):
1147
+ err = data.get("error") if isinstance(data.get("error"), dict) else {}
1148
+ raise SolveAttemptError(f"the pixel route refused ({err.get('code') or r.status_code})")
1149
+ # The collector's own endpoint, not the solver's reconstruction of it (the provider examples do the same).
1150
+ target = pixel_target(collector)
1151
+ await _session_send(session, "POST", target, headers={"content-type": request.get("contentType") or "application/x-www-form-urlencoded", "origin": origin, "referer": url, "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*"}, body=request["body"], kind="xhr", timeout=self.request_timeout)
1152
+ return True
1153
+
1154
+ # -- _abck sensor (WebSocket) ---------------------------------------------------
1155
+
1156
+ async def solve_abck(self, session: Any, url: str, html: str, *, script_url: str | None = None) -> SensorResult:
1157
+ """Runs the ``_abck`` sensor rounds for the page `url` (its `html` as your session got it)."""
1158
+ import websockets
1159
+
1160
+ script_url = script_url or find_sensor_script(html, url)
1161
+ if not script_url:
1162
+ return SensorResult(accepted=False, error="no Akamai sensor script in the page")
1163
+ base, key = self._endpoint()
1164
+ origin = f"{httpx.URL(url).scheme}://{httpx.URL(url).host}"
1165
+ _, script = await _session_send(session, "GET", script_url, headers={"referer": url, "sec-fetch-dest": "script", "sec-fetch-mode": "no-cors", "sec-fetch-site": "same-origin", "accept": "*/*"}, body=None, kind="xhr", timeout=self.request_timeout)
1166
+ init: dict[str, Any] = {
1167
+ "type": "init", "url": url, "script": script, "scriptUrl": script_url, "html": _STRIP_SCRIPTS_RE.sub("", html or ""),
1168
+ "cookies": _cookie_dict(session), "profileId": self.profile_id,
1169
+ }
1170
+ if self.telemetry:
1171
+ init["profile"] = self.telemetry
1172
+ ws_url = re.sub(r"^http", "ws", base, flags=re.I) + "/akamai/session"
1173
+ result = SensorResult(accepted=False)
1174
+ self.sessions += 1
1175
+ deadline = time.monotonic() + self.timeout
1176
+ try:
1177
+ async with _ws_connect(ws_url, {"x-api-key": key}) as ws:
1178
+ await ws.send(json.dumps(init))
1179
+ while True:
1180
+ left = deadline - time.monotonic()
1181
+ if left <= 0:
1182
+ result.error = f"not accepted within {self.timeout:g}s"
1183
+ break
1184
+ try:
1185
+ raw = await asyncio.wait_for(ws.recv(), timeout=left)
1186
+ except asyncio.TimeoutError:
1187
+ result.error = f"not accepted within {self.timeout:g}s"
1188
+ break
1189
+ msg = _json(raw if isinstance(raw, str) else raw.decode("utf-8", "replace"))
1190
+ kind = msg.get("type")
1191
+ if kind == "submission":
1192
+ result.submissions += 1
1193
+ if result.submissions > self.max_rounds:
1194
+ result.error = f"not accepted after {self.max_rounds} rounds"
1195
+ break
1196
+ target = str(msg.get("url") or "")
1197
+ headers = {k: v for k, v in (msg.get("headers") or {}).items() if k.lower() not in _OWN_HEADERS}
1198
+ headers.setdefault("origin", origin)
1199
+ headers.setdefault("referer", url)
1200
+ if not _step_allowed(target, url):
1201
+ await ws.send(json.dumps({"type": "submission_response", "id": msg.get("id"), "status": 0, "body": "Client error: refused a submission outside the target site"}))
1202
+ continue
1203
+ try:
1204
+ status, body = await _session_send(session, str(msg.get("method") or "POST"), target, headers=headers, body=msg.get("body") or "", kind="xhr", timeout=self.request_timeout)
1205
+ except Exception as exc: # noqa: BLE001
1206
+ status, body = 0, f"Client error: {type(exc).__name__}"
1207
+ await ws.send(json.dumps({"type": "submission_response", "id": msg.get("id"), "status": status, "body": body, "cookies": _cookie_dict(session)}))
1208
+ elif kind == "cookie_update":
1209
+ result.rounds = int(msg.get("round") or result.rounds + 1)
1210
+ result.abck = abck_state((msg.get("cookies") or {}).get("_abck")) or result.abck
1211
+ if msg.get("accepted"):
1212
+ result.accepted = True
1213
+ break
1214
+ elif kind == "status" and str(msg.get("state") or "") == "accepted":
1215
+ result.accepted = True
1216
+ break
1217
+ elif kind == "error":
1218
+ result.error = str(msg.get("message") or msg.get("code") or "solver error")[:300]
1219
+ if msg.get("code") == "invalid_request":
1220
+ raise SolverRequestInvalid(result.error)
1221
+ except websockets.exceptions.InvalidHandshake as exc: # a refused upgrade carries the gateway's JSON error
1222
+ status, body, retry_after = _refused_upgrade(exc)
1223
+ if status:
1224
+ check_solver_response(status, body, retry_after)
1225
+ raise SolveAttemptError(f"solver session refused ({status or type(exc).__name__})") from exc
1226
+ except (OSError, asyncio.TimeoutError, websockets.exceptions.WebSocketException) as exc:
1227
+ if not result.accepted:
1228
+ result.error = result.error or f"solver session failed: {type(exc).__name__}"
1229
+ result.abck = abck_state(_cookie_dict(session).get("_abck")) or result.abck
1230
+ if result.accepted:
1231
+ self.accepted += 1
1232
+ return result
1233
+
1234
+ async def solve(self, session: Any, url: str, html: str) -> SensorResult:
1235
+ """SBSD when the page carries a bundle, then the ``_abck`` sensor (on the page as it is after SBSD)."""
1236
+ if find_sbsd_bundle(html, url):
1237
+ await self.solve_sbsd(session, url, html)
1238
+ if not find_sensor_script(html, url) or len(html) < 5000:
1239
+ _, html = await _session_send(session, "GET", url, headers={"referer": url}, body=None, kind="navigate", timeout=self.request_timeout)
1240
+ return await self.solve_abck(session, url, html)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.41
3
+ Version: 0.1.42
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <hello@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0