aiofox 0.2.0__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 (151) hide show
  1. aiofox-0.2.0/LICENSE +22 -0
  2. aiofox-0.2.0/MANIFEST.in +3 -0
  3. aiofox-0.2.0/PKG-INFO +445 -0
  4. aiofox-0.2.0/README.md +385 -0
  5. aiofox-0.2.0/aiofox/VERSION +1 -0
  6. aiofox-0.2.0/aiofox/__init__.py +12 -0
  7. aiofox-0.2.0/aiofox/__main__.py +7 -0
  8. aiofox-0.2.0/aiofox/cmdline.py +178 -0
  9. aiofox-0.2.0/aiofox/commands/__init__.py +197 -0
  10. aiofox-0.2.0/aiofox/commands/crawl.py +40 -0
  11. aiofox-0.2.0/aiofox/commands/genspider.py +174 -0
  12. aiofox-0.2.0/aiofox/commands/list.py +34 -0
  13. aiofox-0.2.0/aiofox/commands/new.py +9 -0
  14. aiofox-0.2.0/aiofox/commands/onespider.py +33 -0
  15. aiofox-0.2.0/aiofox/commands/run.py +85 -0
  16. aiofox-0.2.0/aiofox/commands/runspider.py +82 -0
  17. aiofox-0.2.0/aiofox/commands/shell.py +312 -0
  18. aiofox-0.2.0/aiofox/commands/startproject.py +132 -0
  19. aiofox-0.2.0/aiofox/commands/version.py +36 -0
  20. aiofox-0.2.0/aiofox/core/__init__.py +0 -0
  21. aiofox-0.2.0/aiofox/core/downloader/__init__.py +294 -0
  22. aiofox-0.2.0/aiofox/core/downloader/browser_pool.py +356 -0
  23. aiofox-0.2.0/aiofox/core/downloader/handlers/__init__.py +0 -0
  24. aiofox-0.2.0/aiofox/core/downloader/handlers/_errors.py +67 -0
  25. aiofox-0.2.0/aiofox/core/downloader/handlers/aiohttp.py +121 -0
  26. aiofox-0.2.0/aiofox/core/downloader/handlers/curl_cffi.py +100 -0
  27. aiofox-0.2.0/aiofox/core/downloader/handlers/httpx.py +101 -0
  28. aiofox-0.2.0/aiofox/core/downloader/handlers/playwright.py +344 -0
  29. aiofox-0.2.0/aiofox/core/downloader/handlers/pyhttpx.py +72 -0
  30. aiofox-0.2.0/aiofox/core/downloader/handlers/requests.py +83 -0
  31. aiofox-0.2.0/aiofox/core/downloader/playwright_actions.py +129 -0
  32. aiofox-0.2.0/aiofox/core/engine.py +418 -0
  33. aiofox-0.2.0/aiofox/core/scheduler/__init__.py +158 -0
  34. aiofox-0.2.0/aiofox/core/scheduler/memory.py +113 -0
  35. aiofox-0.2.0/aiofox/core/scheduler/redis.py +106 -0
  36. aiofox-0.2.0/aiofox/core/scraper.py +301 -0
  37. aiofox-0.2.0/aiofox/crawler.py +249 -0
  38. aiofox-0.2.0/aiofox/dupefilters.py +218 -0
  39. aiofox-0.2.0/aiofox/exceptions.py +124 -0
  40. aiofox-0.2.0/aiofox/exporters.py +95 -0
  41. aiofox-0.2.0/aiofox/http/__init__.py +17 -0
  42. aiofox-0.2.0/aiofox/http/request/__init__.py +116 -0
  43. aiofox-0.2.0/aiofox/http/request/form.py +22 -0
  44. aiofox-0.2.0/aiofox/http/request/json.py +22 -0
  45. aiofox-0.2.0/aiofox/http/response/__init__.py +170 -0
  46. aiofox-0.2.0/aiofox/http/response/text.py +221 -0
  47. aiofox-0.2.0/aiofox/inject.py +234 -0
  48. aiofox-0.2.0/aiofox/item.py +129 -0
  49. aiofox-0.2.0/aiofox/libs/__init__.py +0 -0
  50. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/__init__.py +0 -0
  51. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/_utils.py +56 -0
  52. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/cookies.py +186 -0
  53. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/debug.py +67 -0
  54. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/defaultheaders.py +42 -0
  55. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/httperror.py +50 -0
  56. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/hybridrouting.py +111 -0
  57. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/redirect.py +123 -0
  58. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/retry.py +185 -0
  59. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/snapshot.py +108 -0
  60. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/stats.py +82 -0
  61. aiofox-0.2.0/aiofox/libs/downloadermiddlewares/useragent.py +44 -0
  62. aiofox-0.2.0/aiofox/libs/extensions/__init__.py +1 -0
  63. aiofox-0.2.0/aiofox/libs/extensions/corestats.py +53 -0
  64. aiofox-0.2.0/aiofox/libs/extensions/feedexport.py +188 -0
  65. aiofox-0.2.0/aiofox/libs/extensions/logstats.py +66 -0
  66. aiofox-0.2.0/aiofox/libs/httpcache/__init__.py +19 -0
  67. aiofox-0.2.0/aiofox/libs/httpcache/middleware.py +91 -0
  68. aiofox-0.2.0/aiofox/libs/httpcache/policy.py +69 -0
  69. aiofox-0.2.0/aiofox/libs/httpcache/storage.py +78 -0
  70. aiofox-0.2.0/aiofox/libs/job.py +73 -0
  71. aiofox-0.2.0/aiofox/libs/pipelines/__init__.py +12 -0
  72. aiofox-0.2.0/aiofox/libs/pipelines/files.py +271 -0
  73. aiofox-0.2.0/aiofox/libs/pipelines/images.py +126 -0
  74. aiofox-0.2.0/aiofox/libs/statscollectors.py +93 -0
  75. aiofox-0.2.0/aiofox/logformatter.py +117 -0
  76. aiofox-0.2.0/aiofox/middleware/__init__.py +10 -0
  77. aiofox-0.2.0/aiofox/middleware/adaptive_concurrency.py +107 -0
  78. aiofox-0.2.0/aiofox/middleware/downloader.py +80 -0
  79. aiofox-0.2.0/aiofox/middleware/extension.py +18 -0
  80. aiofox-0.2.0/aiofox/middleware/itempipeline.py +29 -0
  81. aiofox-0.2.0/aiofox/middleware/manager.py +122 -0
  82. aiofox-0.2.0/aiofox/py.typed +0 -0
  83. aiofox-0.2.0/aiofox/queue/__init__.py +64 -0
  84. aiofox-0.2.0/aiofox/queue/compat.py +61 -0
  85. aiofox-0.2.0/aiofox/queue/convert.py +123 -0
  86. aiofox-0.2.0/aiofox/queue/memory/__init__.py +9 -0
  87. aiofox-0.2.0/aiofox/queue/memory/_queue.py +58 -0
  88. aiofox-0.2.0/aiofox/queue/rabbitmq/__init__.py +9 -0
  89. aiofox-0.2.0/aiofox/queue/rabbitmq/_queue.py +116 -0
  90. aiofox-0.2.0/aiofox/queue/redis/__init__.py +13 -0
  91. aiofox-0.2.0/aiofox/queue/redis/_queue.py +79 -0
  92. aiofox-0.2.0/aiofox/queue/redis/_queue_async.py +296 -0
  93. aiofox-0.2.0/aiofox/settings/__init__.py +490 -0
  94. aiofox-0.2.0/aiofox/settings/default_settings.py +224 -0
  95. aiofox-0.2.0/aiofox/signalmanager.py +75 -0
  96. aiofox-0.2.0/aiofox/signals.py +33 -0
  97. aiofox-0.2.0/aiofox/spider.py +85 -0
  98. aiofox-0.2.0/aiofox/templates/project/__init__.py +0 -0
  99. aiofox-0.2.0/aiofox/templates/project/aiofox.cfg +9 -0
  100. aiofox-0.2.0/aiofox/templates/project/middlewares.py.tmpl +43 -0
  101. aiofox-0.2.0/aiofox/templates/project/pipelines.py.tmpl +4 -0
  102. aiofox-0.2.0/aiofox/templates/project/settings.py.tmpl +119 -0
  103. aiofox-0.2.0/aiofox/templates/project/spiders/__init__.py +4 -0
  104. aiofox-0.2.0/aiofox/templates/project/start.py.tmpl +24 -0
  105. aiofox-0.2.0/aiofox/templates/spiders/basic.tmpl +17 -0
  106. aiofox-0.2.0/aiofox/templates/spiders/crawl.tmpl +34 -0
  107. aiofox-0.2.0/aiofox/utils/__init__.py +1 -0
  108. aiofox-0.2.0/aiofox/utils/common.py +103 -0
  109. aiofox-0.2.0/aiofox/utils/curl.py +134 -0
  110. aiofox-0.2.0/aiofox/utils/headers.py +112 -0
  111. aiofox-0.2.0/aiofox/utils/log.py +222 -0
  112. aiofox-0.2.0/aiofox/utils/ossignal.py +28 -0
  113. aiofox-0.2.0/aiofox/utils/othtypes.py +135 -0
  114. aiofox-0.2.0/aiofox/utils/signal.py +63 -0
  115. aiofox-0.2.0/aiofox/utils/template.py +38 -0
  116. aiofox-0.2.0/aiofox/utils/tools.py +325 -0
  117. aiofox-0.2.0/aiofox.egg-info/PKG-INFO +445 -0
  118. aiofox-0.2.0/aiofox.egg-info/SOURCES.txt +149 -0
  119. aiofox-0.2.0/aiofox.egg-info/dependency_links.txt +1 -0
  120. aiofox-0.2.0/aiofox.egg-info/entry_points.txt +2 -0
  121. aiofox-0.2.0/aiofox.egg-info/not-zip-safe +1 -0
  122. aiofox-0.2.0/aiofox.egg-info/requires.txt +45 -0
  123. aiofox-0.2.0/aiofox.egg-info/top_level.txt +1 -0
  124. aiofox-0.2.0/pyproject.toml +119 -0
  125. aiofox-0.2.0/setup.cfg +4 -0
  126. aiofox-0.2.0/setup.py +3 -0
  127. aiofox-0.2.0/tests/test_adaptive_concurrency.py +185 -0
  128. aiofox-0.2.0/tests/test_builtin_middlewares.py +967 -0
  129. aiofox-0.2.0/tests/test_cli_commands.py +311 -0
  130. aiofox-0.2.0/tests/test_crawl_e2e.py +947 -0
  131. aiofox-0.2.0/tests/test_debugging.py +447 -0
  132. aiofox-0.2.0/tests/test_downloader_signals.py +177 -0
  133. aiofox-0.2.0/tests/test_downloader_slots.py +317 -0
  134. aiofox-0.2.0/tests/test_dupefilter.py +162 -0
  135. aiofox-0.2.0/tests/test_engine_memory_management.py +101 -0
  136. aiofox-0.2.0/tests/test_engine_request_tracking.py +253 -0
  137. aiofox-0.2.0/tests/test_engine_task_beat.py +93 -0
  138. aiofox-0.2.0/tests/test_error_logs.py +118 -0
  139. aiofox-0.2.0/tests/test_feed_export.py +375 -0
  140. aiofox-0.2.0/tests/test_files_pipeline.py +456 -0
  141. aiofox-0.2.0/tests/test_graceful_shutdown.py +192 -0
  142. aiofox-0.2.0/tests/test_httpx_handler.py +134 -0
  143. aiofox-0.2.0/tests/test_jobdir.py +293 -0
  144. aiofox-0.2.0/tests/test_middlewares_e2e.py +378 -0
  145. aiofox-0.2.0/tests/test_playwright_pool.py +923 -0
  146. aiofox-0.2.0/tests/test_py312_upgrade.py +116 -0
  147. aiofox-0.2.0/tests/test_queue_convert.py +76 -0
  148. aiofox-0.2.0/tests/test_redis_scheduler.py +479 -0
  149. aiofox-0.2.0/tests/test_retry_middleware.py +174 -0
  150. aiofox-0.2.0/tests/test_stats.py +48 -0
  151. aiofox-0.2.0/tests/test_type_annotations.py +105 -0
aiofox-0.2.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 ihandmine
4
+ Copyright (c) 2026 izetaiota
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ recursive-include aiofox VERSION
2
+ recursive-include aiofox/templates/project *.tmpl *.cfg *.py
3
+ recursive-include aiofox/templates/spiders *.tmpl
aiofox-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,445 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiofox
3
+ Version: 0.2.0
4
+ Summary: An asyncio-based web crawling and scraping framework
5
+ Author-email: izetaiota <zetaiota95@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/izetaiota/Aiofox
8
+ Project-URL: Repository, https://github.com/izetaiota/Aiofox
9
+ Project-URL: Issues, https://github.com/izetaiota/Aiofox/issues
10
+ Keywords: crawler,scrapy,asyncio,aiohttp,httpx,anti-header,anti-useragent,python3
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Operating System :: Unix
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.12
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: aiohttp
24
+ Requires-Dist: httpx
25
+ Requires-Dist: requests
26
+ Requires-Dist: anti-header
27
+ Requires-Dist: anti-useragent
28
+ Requires-Dist: w3lib
29
+ Requires-Dist: parsel
30
+ Requires-Dist: PyDispatcher
31
+ Requires-Dist: redis
32
+ Requires-Dist: anyio
33
+ Requires-Dist: ujson
34
+ Requires-Dist: loguru
35
+ Provides-Extra: all
36
+ Requires-Dist: cryptography; extra == "all"
37
+ Requires-Dist: httpx[http2]>=0.23.0; extra == "all"
38
+ Requires-Dist: curl_cffi; extra == "all"
39
+ Requires-Dist: pika; extra == "all"
40
+ Provides-Extra: aiohttp
41
+ Requires-Dist: aiohttp; extra == "aiohttp"
42
+ Requires-Dist: cryptography; extra == "aiohttp"
43
+ Provides-Extra: httpx
44
+ Requires-Dist: httpx[http2]>=0.23.0; extra == "httpx"
45
+ Provides-Extra: requests
46
+ Requires-Dist: requests; extra == "requests"
47
+ Provides-Extra: curl-cffi
48
+ Requires-Dist: curl_cffi; extra == "curl-cffi"
49
+ Provides-Extra: rabbitmq
50
+ Requires-Dist: pika; extra == "rabbitmq"
51
+ Provides-Extra: playwright
52
+ Requires-Dist: playwright; extra == "playwright"
53
+ Provides-Extra: images
54
+ Requires-Dist: Pillow>=10; extra == "images"
55
+ Provides-Extra: dev
56
+ Requires-Dist: mypy>=2.4; extra == "dev"
57
+ Requires-Dist: fakeredis[lua]>=2.24; extra == "dev"
58
+ Requires-Dist: Pillow>=10; extra == "dev"
59
+ Dynamic: license-file
60
+
61
+ <p align="center">
62
+ <img src="./doc/images/aiofox-logo.svg" alt="AIOFOX - Hybrid HTTP & Playwright Scraping Framework" width="100%">
63
+ </p>
64
+
65
+ <p align="center">
66
+ <strong>English</strong> β€’ <a href="./doc/README_ZH.md">δΈ­ζ–‡ζ–‡ζ‘£</a> β€’ <a href="./ROADMAP.md">Roadmap</a> β€’ <a href="./CHANGELOG.md">Changelog</a> β€’ <a href="./LICENSE">MIT License</a>
67
+ </p>
68
+
69
+ **Aiofox** is a fast, high-level asynchronous web crawling and scraping framework built on **Python 3.12+ asyncio**. Derived from [aioscpy](https://github.com/ihandmine/aioscpy), it keeps the Scrapy-style developer experience while modernizing the engine, HTTP backends, packaging, and distributed scheduling for the current Python ecosystem.
70
+
71
+ > **Status:** hybrid HTTP + Playwright rendering, crawl resume (graceful shutdown, `JOBDIR`, Redis queue with acknowledgements), opt-in downloader middlewares and an HTTP cache, `FilesPipeline` / `ImagesPipeline`, `aiofox shell`, full type annotations, built-in retry and duplicate filtering, per-domain concurrency, `Item` validation and feed export are released as **v0.2.0** (see the [Changelog](./CHANGELOG.md)). Advanced anti-block features are still on the roadmap.
72
+
73
+ ## ✨ Features
74
+
75
+ ### Available Now
76
+
77
+ - **Scrapy-style API, fully asyncio-native** β€” `Spider`, `Request` / `FormRequest` / `JsonRequest`, `TextResponse` (CSS / XPath / `follow` / `follow_all` / `await response.json`), downloader middlewares, item pipelines, extensions, 14 signals, and priority-aware `Settings`.
78
+ - **Hybrid HTTP + Playwright in one spider** β€” flag the requests that need JavaScript with `meta["playwright"] = True`; they are rendered by a pooled browser (optional extra) with `session_id` context isolation, resource blocking, wait strategies and automatic restart after a crash, while every other request keeps going through HTTP.
79
+ - **5 pluggable HTTP backends** β€” `httpx` (default), `aiohttp`, `requests`, `curl_cffi`, and `pyhttpx`, switched with a single `DOWNLOAD_HANDLER` setting.
80
+ - **Built-in reliability** β€” per-domain concurrency and delay slots, `RetryMiddleware` with exponential backoff that honours `Retry-After`, and a memory `DupeFilter` wired into the scheduler.
81
+ - **Crawl resume & graceful shutdown** β€” `Ctrl+C` / `SIGTERM` close the open spiders the normal way (in-flight requests go back to the scheduler, `finish_reason` is `shutdown`); set `JOBDIR` and the queue, the in-flight requests and the seen fingerprints survive an interruption; the Redis queue acknowledges requests and hands a dead worker's in-flight requests back to the queue.
82
+ - **Opt-in downloader middlewares & HTTP cache** β€” all registered in `DOWNLOADER_MIDDLEWARES_BASE`, each off until its setting turns it on: auto-routing of pages that turn out to need JavaScript to the browser, `DEFAULT_HEADERS` / `USER_AGENT` (a list value is picked per domain and kept), redirects with cross-host credential stripping, cookies with named jars, non-2xx filtering, and a disk HTTP cache; verbose logging and response snapshots for debugging.
83
+ - **Item model and feed export** β€” declarative `Item` / `Field` with validation before the pipelines, and JSON Lines / CSV export through `-o` / `-O` / `-t` or the `FEEDS` setting.
84
+ - **Media pipelines & `engine.download()`** β€” `FilesPipeline` / `ImagesPipeline` download the URLs an item lists and store them by content hash (SHA-1, no duplicates), with thumbnails and size filters for images (Pillow); `await crawler.engine.download(request, spider)` bypasses the scheduler but keeps every downloader middleware.
85
+ - **Playwright page actions & screenshots** β€” declarative `playwright_page_action` steps (click / fill / press / scroll / wait) or a callable receiving the page, screenshots into the response meta or to disk, per-request `playwright_cookies` / `playwright_proxy`, and context fingerprint settings (`PLAYWRIGHT_USER_AGENT`, `PLAYWRIGHT_VIEWPORT`, `PLAYWRIGHT_LOCALE`, `PLAYWRIGHT_TIMEZONE_ID`).
86
+ - **Distributed crawling with Redis** β€” `RedisScheduler` backed by `redis.asyncio` sorted-set priority queues with per-worker heartbeats and in-flight recovery, `RedisDupeFilter` sharing fingerprints across workers, plus a synchronous producer queue for external task feeders.
87
+ - **Debugging CLI & typed package** β€” `aiofox shell` interactive console (`fetch` / `view` / `--snapshot`, runs with the project's settings and middlewares) and `aiofox list`; the whole package is type-annotated and ships `py.typed`, checked with mypy (`pip install "aiofox[dev]"` then `python -m mypy`).
88
+ - **Adaptive concurrency & backpressure** β€” optional `AdaptiveConcurrencyMiddleware` that tunes concurrency from response latency, plus downloader/scraper backpressure and heartbeat-driven garbage collection.
89
+ - **Proxy & TLS control per request** β€” `meta["proxy"]`, random TLS cipher suites, and browser impersonation via `curl_cffi` (`TLS_CIPHERS`).
90
+ - **Lightweight dependency injection & loguru logging** β€” automatic `self.di` / `self.logger` injection, console Unicode icon auto-detection, and file log rotation.
91
+
92
+ ### 🚧 Roadmap Highlights (see [ROADMAP.md](./ROADMAP.md))
93
+
94
+ - **`v0.1.x` (MVP)** β€” shipped in `v0.2.0`: hybrid HTTP + Playwright browser pool (`meta["playwright"] = True`, resource blocking, `session_id` context isolation, crash restart), memory `DupeFilter`, per-domain concurrency slots, exponential-backoff `RetryMiddleware`, `Item` validation + JSONL/CSV export (`-o`), and `aiofox new` / `aiofox run` CLI shortcuts.
95
+ - **`v0.2.x` (Stable Beta)** β€” shipped in `v0.2.0`: crawl resume (graceful shutdown, `JOBDIR`, crash-safe Redis queue, `RedisDupeFilter`), opt-in downloader middlewares (auto browser routing, headers / UA, redirects, cookies, HTTP error filtering, HTTP cache), Playwright page actions / screenshots / per-request cookies & proxies / context fingerprint settings, `engine.download()`, `FilesPipeline` / `ImagesPipeline`, `aiofox shell` / `aiofox list`, full type annotations with `py.typed` + mypy. Still open: MongoDB / MySQL sample pipelines.
96
+ - **`v0.3.x ~ v1.0.0` (Ecosystem)** β€” Proxy pool with health checks (`http` / `https` / `socks5`), anti-crawl detection markers, Prometheus metrics, optional Web UI plugin, distributed sharding, and Docker deployment.
97
+
98
+ ## πŸ“¦ Requirements & Installation
99
+
100
+ - **Python 3.12+** (Linux, Windows, macOS, BSD)
101
+
102
+ ```shell
103
+ # Basic install
104
+ pip install aiofox
105
+
106
+ # All optional dependencies
107
+ pip install aiofox[all]
108
+
109
+ # Specific HTTP backend
110
+ pip install aiofox[aiohttp,httpx]
111
+
112
+ # Browser rendering, image pipelines, development & testing tools
113
+ pip install "aiofox[playwright]"
114
+ pip install "aiofox[images]"
115
+ pip install "aiofox[dev]"
116
+
117
+ # Latest version from GitHub
118
+ pip install git+https://github.com/izetaiota/Aiofox
119
+ ```
120
+
121
+ ### Install from Source
122
+
123
+ ```shell
124
+ git clone https://github.com/izetaiota/Aiofox.git
125
+ cd Aiofox
126
+ python -m venv .venv
127
+ source .venv/bin/activate # Windows Git Bash: source .venv/Scripts/activate
128
+ pip install -e .
129
+ ```
130
+
131
+ ### Optional Extras
132
+
133
+ | Extra | Installs | Use Case |
134
+ |---|---|---|
135
+ | `aiofox[httpx]` | `httpx[http2]` | HTTP/2 support for the default `HttpxDownloadHandler` |
136
+ | `aiofox[aiohttp]` | `aiohttp`, `cryptography` | `AioHttpDownloadHandler` |
137
+ | `aiofox[requests]` | `requests` | `RequestsDownloadHandler` |
138
+ | `aiofox[curl_cffi]` | `curl_cffi` | Browser TLS impersonation via `CurlCffiDownloadHandler` |
139
+ | `aiofox[rabbitmq]` | `pika` | RabbitMQ priority queue utilities |
140
+ | `aiofox[playwright]` | `playwright` | Browser rendering for requests with `meta["playwright"] = True`; run `playwright install chromium` afterwards |
141
+ | `aiofox[images]` | `Pillow` | `ImagesPipeline` thumbnails and size filters |
142
+ | `aiofox[dev]` | `mypy`, `fakeredis[lua]`, `Pillow` | Type checking and the test suite (the Redis tests run on fakeredis) |
143
+ | `aiofox[all]` | all optional HTTP & queue extras | Everything except the `playwright`, `images` and `dev` extras |
144
+
145
+ ## πŸš€ Quick Start
146
+
147
+ ### Create a Project and a Spider
148
+
149
+ ```shell
150
+ aiofox startproject myproject # aiofox new myproject does the same
151
+ cd myproject
152
+ aiofox genspider myspider
153
+
154
+ # or generate a standalone single-file spider
155
+ aiofox onespider single_quotes
156
+ ```
157
+
158
+ ### Example: HTTP Spider
159
+
160
+ ```python
161
+ from aiofox.spider import Spider
162
+
163
+
164
+ class QuotesSpider(Spider):
165
+ name = 'quotes'
166
+ custom_settings = {
167
+ "SPIDER_IDLE": False
168
+ }
169
+ start_urls = [
170
+ 'https://quotes.toscrape.com/tag/humor/',
171
+ ]
172
+
173
+ async def parse(self, response):
174
+ for quote in response.css('div.quote'):
175
+ yield {
176
+ 'author': quote.xpath('span/small/text()').get(),
177
+ 'text': quote.css('span.text::text').get(),
178
+ }
179
+
180
+ next_page = response.css('li.next a::attr("href")').get()
181
+ if next_page is not None:
182
+ yield response.follow(next_page, self.parse)
183
+ ```
184
+
185
+ ### Example: Hybrid Spider (HTTP + Browser)
186
+
187
+ The listing under `/js/` is built by a page script, so its requests are flagged for the browser; nothing else changes.
188
+
189
+ ```python
190
+ from aiofox.http import Request
191
+ from aiofox.item import Field, Item
192
+ from aiofox.spider import Spider
193
+
194
+
195
+ class QuoteItem(Item):
196
+ text = Field(py_type=str, required=True)
197
+ author = Field(py_type=str)
198
+
199
+
200
+ class JsQuotesSpider(Spider):
201
+ name = 'js_quotes'
202
+ start_urls = ['https://quotes.toscrape.com/js/']
203
+
204
+ async def start_requests(self):
205
+ yield Request(self.start_urls[0], meta={'playwright': True})
206
+
207
+ async def parse(self, response):
208
+ # the DOM after the browser ran the page script
209
+ for quote in response.css('div.quote'):
210
+ yield QuoteItem(text=quote.css('span.text::text').get(),
211
+ author=quote.css('small.author::text').get())
212
+ next_page = response.css('li.next a::attr(href)').get()
213
+ if next_page is not None:
214
+ yield response.follow(next_page, meta={'playwright': True})
215
+ ```
216
+
217
+ A larger runnable example that mixes static pages, author pages and JS pages in one crawl lives in [`example/hybrid_quotes.py`](./example/hybrid_quotes.py). [`example/auto_routing_quotes.py`](./example/auto_routing_quotes.py) shows the opt-in auto-routing instead: every page is first requested over HTTP, and only the pages whose quotes are missing from the response are re-requested in the browser.
218
+
219
+ ### Run Spiders
220
+
221
+ ```shell
222
+ # Run a spider inside a project, exporting the items as JSON Lines
223
+ aiofox crawl quotes -o quotes.jsonl
224
+
225
+ # Run a standalone spider file (aiofox run quotes.py does the same)
226
+ aiofox runspider quotes.py
227
+
228
+ # Inside a project that defines exactly one spider
229
+ aiofox run
230
+
231
+ # Inspect a page in an interactive console (fetch / view / --snapshot)
232
+ aiofox shell https://quotes.toscrape.com/page/2/
233
+
234
+ # List the spiders a project defines
235
+ aiofox list
236
+
237
+ # List all CLI commands
238
+ aiofox -h
239
+ ```
240
+
241
+ ### Run from Python Code
242
+
243
+ ```python
244
+ from aiofox.crawler import call_grace_instance
245
+ from aiofox.utils.tools import get_project_settings
246
+
247
+
248
+ def load_spiders_from_directory():
249
+ process = call_grace_instance("crawler_process", get_project_settings())
250
+ process.load_spider(path='./spiders')
251
+ process.start()
252
+
253
+
254
+ def run_specific_spider():
255
+ process = call_grace_instance("crawler_process", get_project_settings())
256
+ process.crawl('myspider')
257
+ process.start()
258
+
259
+
260
+ if __name__ == '__main__':
261
+ run_specific_spider()
262
+ ```
263
+
264
+ ## πŸ“Œ Request Meta Reference
265
+
266
+ | Key | Type | Status | Description |
267
+ |---|---|---|---|
268
+ | `proxy` | `str \| dict` | βœ… `v0.1.x` | Per-request proxy (`httpx` also accepts a dict for scheme-specific `mounts`) |
269
+ | `TLS_CIPHERS` | `bool` | βœ… `v0.1.x` | Enable random TLS cipher suites or `curl_cffi` browser impersonation for this request |
270
+ | `allow_redirects` | `bool` | βœ… `v0.1.x` | Follow redirects in `RequestsDownloadHandler` (default `True`) |
271
+ | `playwright` | `bool` | βœ… `v0.1.x` | Route this request through the Playwright browser pool (HTTP is the default) |
272
+ | `playwright_block_resources` | `bool \| list` | βœ… `v0.1.x` | Resource types to block in browser mode (default `image` / `media` / `font`; `False` blocks nothing) |
273
+ | `session_id` | `str` | βœ… `v0.1.x` | Bind the request to a dedicated browser context (cookies & storage) kept for the whole crawl |
274
+ | `playwright_wait_until` | `str` | βœ… `v0.1.x` | Navigation stop condition for this request: `load` / `domcontentloaded` / `networkidle` / `commit` |
275
+ | `playwright_wait_for` | `str` | βœ… `v0.1.x` | CSS selector that must appear before the rendered HTML is captured |
276
+ | `download_slot` | `str` | βœ… `v0.1.x` | Share one concurrency / delay slot between requests (default: one slot per hostname) |
277
+ | `dont_retry` | `bool` | βœ… `v0.1.x` | Skip the built-in retry middleware for this request |
278
+ | `playwright_timeout` | `int` | βœ… `v0.2.x` | Per-request browser time budget in **seconds**; navigation, waits, page actions and screenshots share it (default `PLAYWRIGHT_PAGE_TIMEOUT = 30`) |
279
+ | `playwright_screenshot` | `bool \| dict` | βœ… `v0.2.x` | Capture a page screenshot (`True`, or options of `Page.screenshot()`); the PNG bytes land in `response.meta["playwright_screenshot"]` |
280
+ | `playwright_screenshot_path` | `str` | βœ… `v0.2.x` | Write the screenshot to this path; when it names a directory the file name is hashed from the URL and the path ends up in `response.meta["playwright_screenshot_file"]` |
281
+ | `playwright_proxy` | `str` | βœ… `v0.2.x` | Bind a proxy to the browser context created for this request (fixed when the context is first created) |
282
+ | `playwright_cookies` | `dict \| list` | βœ… `v0.2.x` | Browser cookies for this request; it gets a one-off context so they do not leak into other sessions |
283
+ | `playwright_page_action` | `callable \| dict \| list` | βœ… `v0.2.x` | Page actions before the HTML is captured: a callable receiving the page, or declarative steps (`click` / `fill` / `press` / `scroll` / `wait_for` / `wait`) |
284
+
285
+ ## βš™οΈ Configuration & Distributed Crawling
286
+
287
+ Configure in your project `settings.py` or in `Spider.custom_settings`:
288
+
289
+ ### Concurrency & Downloading
290
+
291
+ ```python
292
+ # Concurrency
293
+ CONCURRENT_ITEMS = 100
294
+ CONCURRENT_REQUESTS = 16
295
+ CONCURRENT_REQUESTS_PER_DOMAIN = 8
296
+ CONCURRENT_REQUESTS_PER_IP = 0
297
+
298
+ # Delay & timeout (seconds)
299
+ DOWNLOAD_DELAY = 0
300
+ DOWNLOAD_TIMEOUT = 20
301
+ RANDOMIZE_DOWNLOAD_DELAY = True
302
+
303
+ # HTTP backend
304
+ DOWNLOAD_HANDLER = "aiofox.core.downloader.handlers.aiohttp.AioHttpDownloadHandler"
305
+ # Other options:
306
+ # DOWNLOAD_HANDLER = "aiofox.core.downloader.handlers.httpx.HttpxDownloadHandler" # default
307
+ # DOWNLOAD_HANDLER = "aiofox.core.downloader.handlers.requests.RequestsDownloadHandler"
308
+ # DOWNLOAD_HANDLER = "aiofox.core.downloader.handlers.curl_cffi.CurlCffiDownloadHandler"
309
+ ```
310
+
311
+ ### Redis Distributed Crawling
312
+
313
+ ```python
314
+ # Scheduler (memory by default; switch to RedisScheduler for distributed mode)
315
+ SCHEDULER = "aiofox.core.scheduler.redis.RedisScheduler"
316
+ DUPEFILTER_CLASS = "aiofox.dupefilters.RedisDupeFilter"
317
+
318
+ # Redis connection
319
+ REDIS_URI = "redis://localhost:6379"
320
+ QUEUE_KEY = "%(spider)s:requests"
321
+ REDIS_WORKER_TTL = 30 # seconds without a heartbeat before a worker counts as dead
322
+ REDIS_INFLIGHT_TIMEOUT = 600 # seconds a request may stay in flight before it is handed back
323
+ ```
324
+
325
+ Run the same spider on multiple machines pointing at the same Redis server to consume the queue together. A request taken from the queue stays in flight until its result is processed; when a worker dies, its in-flight requests go back to the queue and the surviving workers pick them up.
326
+
327
+ ### Retries, Duplicate Filtering & Browser Rendering
328
+
329
+ ```python
330
+ # Built-in retry: timeouts, connection errors and these status codes, with exponential backoff
331
+ RETRY_ENABLED = True
332
+ RETRY_TIMES = 2
333
+ RETRY_HTTP_CODES = [408, 429, 500, 502, 503, 504, 522, 524]
334
+
335
+ # Duplicate requests are dropped before they are scheduled (None disables it;
336
+ # keep a request out of it with Request(url, dont_filter=True))
337
+ DUPEFILTER_CLASS = "aiofox.dupefilters.MemoryDupeFilter"
338
+
339
+ # Browser requests (meta["playwright"] = True); the browser starts lazily on the first one
340
+ PLAYWRIGHT_MAX_PAGES = 4 # pages rendered at once, across all domains
341
+ PLAYWRIGHT_BLOCK_RESOURCES = ["image", "media", "font"]
342
+ PLAYWRIGHT_WAIT_UNTIL = "load" # or networkidle for pages that fill in later
343
+ ```
344
+
345
+ ### Middlewares, Caching & Crawl Resume
346
+
347
+ ```python
348
+ # Opt-in downloader middlewares (all registered in DOWNLOADER_MIDDLEWARES_BASE,
349
+ # each off until its setting turns it on)
350
+ REDIRECT_ENABLED = True # follow redirects in the engine
351
+ COOKIES_ENABLED = True # remember cookies and send them back
352
+ HTTPCACHE_ENABLED = True # serve repeated requests from disk
353
+ HTTPERROR_ENABLED = True # drop responses with disallowed status codes
354
+ DEFAULT_HEADERS = {"Accept-Language": "zh-CN,zh;q=0.9"}
355
+ USER_AGENT = ["Mozilla/5.0 …", "Mozilla/5.0 …"] # str, list (picked per domain) or callable
356
+
357
+ # Send pages that turn out to need JavaScript to the browser automatically
358
+ AUTO_BROWSER_ENABLED = True
359
+
360
+ # Crawl resume: queue, in-flight requests and fingerprints survive Ctrl+C
361
+ JOBDIR = "crawl-state/my_spider" # directory for the crawl state
362
+ SHUTDOWN_TIMEOUT = 10 # seconds spiders get to close on Ctrl+C / SIGTERM
363
+ ```
364
+
365
+ ### Response Parsing API
366
+
367
+ ```python
368
+ # CSS selectors
369
+ title = response.css('title::text').get()
370
+ all_links = response.css('a::attr(href)').getall()
371
+
372
+ # XPath
373
+ title = response.xpath('//title/text()').get()
374
+ all_links = response.xpath('//a/@href').getall()
375
+
376
+ # Follow links
377
+ yield response.follow('next-page.html', self.parse)
378
+ yield from response.follow_all(css='a.product::attr(href)', callback=self.parse_product)
379
+ ```
380
+
381
+ ## πŸ“– Documentation
382
+
383
+ The full documentation lives in [`doc/`](./doc/):
384
+
385
+ | Document | Description |
386
+ |---|---|
387
+ | [Documentation Index (δΈ­ζ–‡)](./doc/README_ZH.md) | Central documentation hub |
388
+ | [English Overview](./doc/README_EN.md) | English summary and quick links |
389
+ | [Quick Start & CLI](./doc/quickstart.md) | Installation, CLI commands, `aiofox.cfg`, Spider / Request / Response API |
390
+ | [Architecture](./doc/architecture.md) | Async data flow, dependency injection, `task_beat` / `heart_beat`, backpressure |
391
+ | [Settings Reference](./doc/settings.md) | All settings with priorities and `AIOFOX_*` environment variables |
392
+ | [Core Components](./doc/components.md) | HTTP backends, schedulers, dupefilter, middlewares, `Item` model, pipelines, extensions, signals, logging |
393
+ | [Crawl Resume & Redis](./doc/persistence.md) | Graceful shutdown on Ctrl+C, `JOBDIR` resume on one machine, Redis queue with acknowledgements and in-flight recovery, `RedisDupeFilter` |
394
+ | [Downloader Middlewares & Cache](./doc/middlewares.md) | The opt-in built-in middlewares: auto browser routing, headers / UA, redirects, cookies, HTTP error filtering, HTTP cache; writing your own |
395
+ | [Files & Images Pipelines](./doc/pipelines.md) | `FilesPipeline` / `ImagesPipeline`, content-hash storage, thumbnails and size filters, `engine.download()` |
396
+ | [Debugging Tools](./doc/debugging.md) | `aiofox shell`, `aiofox list`, verbose logging, offline snapshots, type checking |
397
+ | [Playwright Browser Rendering](./doc/playwright.md) | Per-request HTTP / browser routing, waits, `session_id` isolation, page actions, screenshots, per-request cookies & proxies, crash recovery |
398
+ | [Practical Examples](./doc/examples.md) | POST requests, proxies, built-in retry, Item model and JSONL/CSV export, custom pipelines, JS pages, auto browser routing, HTTP cache, file / image pipelines, crawl resume, Redis producers, multi-spider runs |
399
+ | [API Reference](./doc/api-reference.md) | `Settings`, `StatsCollector`, queues, `JobDir`, media pipelines, snapshot helpers, `call_grace_instance`, `aiofox.utils` |
400
+ | [FAQ & Troubleshooting](./doc/faq.md) | Redis callback rules, empty `start_urls`, `custom_settings` scope, `Settings.freeze`, resume after Ctrl+C, unencodable requests, files not downloading, performance |
401
+ | [Migration from aioscpy](./doc/migrate-from-aioscpy.md) | Rename mapping, step-by-step migration, Python 3.12 changes |
402
+ | [Testing & Contributing](./doc/testing-and-contributing.md) | Unit tests, coverage, profiling, type checking, PEP 621 packaging |
403
+ | [Roadmap](./ROADMAP.md) | Versioned roadmap (`v0.1.x` MVP β†’ `v1.0.0`) & design tradeoffs |
404
+ | [Gap Analysis & Backlog (δΈ­ζ–‡)](./doc/gap-analysis.md) | Competitor gap analysis (Scrapy / Crawlee / scrapy-playwright / aioscpy), code-verified status, P1–P6 priorities, known defects |
405
+ | [Changelog](./CHANGELOG.md) | Release history |
406
+
407
+ ## πŸ§ͺ Testing
408
+
409
+ ```shell
410
+ python -W default -m tests.run_tests
411
+ ```
412
+
413
+ The suite runs 424 tests (about five minutes); the end-to-end crawls dominate the runtime because each waits for the engine's 5-second idle heartbeat. The browser tests skip themselves unless the optional extra and a browser binary are installed (`pip install "aiofox[playwright]" && python -m playwright install chromium`), as do the Redis tests without `fakeredis` and the image-pipeline tests without Pillow (`pip install "aiofox[dev]"` installs both).
414
+
415
+ Type check the package with (configuration in `pyproject.toml` under `[tool.mypy]`):
416
+
417
+ ```shell
418
+ pip install "aiofox[dev]"
419
+ python -m mypy
420
+ ```
421
+
422
+ See [Testing & Contributing](./doc/testing-and-contributing.md) for coverage, end-to-end smoke tests, and profiling.
423
+
424
+ ## ⚠️ Important Notes
425
+
426
+ 1. Browser requests go through the same downloader middlewares as HTTP requests (retry, stats, adaptive concurrency, HTTP cache; redirects are handled by the browser itself), but a `Request`'s own headers and body are not forwarded to the browser β€” its user agent comes from `PLAYWRIGHT_USER_AGENT`, and cookies / proxies go through `meta["playwright_cookies"]` / `meta["playwright_proxy"]`.
427
+ 2. Browser rendering is far more resource-intensive than plain HTTP; keep its concurrency low.
428
+ 3. Anti-block components only improve success rates and cannot guarantee bypassing every protection layer.
429
+ 4. Use this project only for lawful public-data collection and comply with the target site's `robots.txt` and applicable laws.
430
+
431
+ ## 🀝 Contributing & Acknowledgements
432
+
433
+ Issues and pull requests are welcome.
434
+
435
+ Aiofox stands on the shoulders of these excellent open-source projects:
436
+
437
+ - [aioscpy](https://github.com/ihandmine/aioscpy) β€” upstream project
438
+ - [Scrapy](https://github.com/scrapy/scrapy)
439
+ - [aiohttp](https://github.com/aio-libs/aiohttp/)
440
+ - [httpx](https://github.com/encode/httpx)
441
+ - [loguru](https://github.com/Delgan/loguru)
442
+
443
+ ## License
444
+
445
+ [MIT](./LICENSE) Β© 2022 ihandmine, 2026 izetaiota