轻量级重试下载器,专为爬虫工程师设计
Project description
bw-retry-downloader
轻量级重试下载器,专为爬虫工程师设计。
确保每个请求都有结果 —— 成功返回数据,失败返回原因,任务不丢失。
特性
- 三层重试补偿:快速重试 → 指数退避 → 放弃并记录,覆盖各类失败场景
- 完整的失败上报:每个失败任务都有原因、尝试次数、业务元数据(meta)
- 失败任务可重跑:
report.failed_tasks()直接取出失败任务重新提交 - 线程池并发:开箱即用,适合 500-1000 个请求的小规模采集
- 钩子机制:请求前/响应后钩子,支持动态代理、验证码检测等
- 429 智能处理:自动读取
Retry-After响应头 - 确定性 task_id:相同请求生成相同 ID,支持幂等去重
安装
pip install bw-retry-downloader
快速上手
from bw_retry_downloader import Downloader, Task
# 创建下载器
dl = Downloader(workers=10)
# 添加任务(meta 挂载业务数据,失败时原样带回)
tasks = [
Task(
url=f"https://api.example.com/item/{i}",
meta={"product_id": i}
)
for i in range(500)
]
dl.add_tasks(tasks)
# 运行并获取报告
report = dl.run()
print(report.summary())
# 下载完成: 总计=500 成功=487 失败=13
# 失败上报给业务
for r in report.failed:
print(f"失败: {r.task.url} | 原因: {r.error} | meta: {r.task.meta}")
# 重跑失败任务
if report.failed_count > 0:
dl.add_tasks(report.failed_tasks())
report2 = dl.run()
进阶用法
自定义重试策略
from bw_retry_downloader import Downloader, RetryPolicy
policy = RetryPolicy(
fast_retries=3, # 快速重试 3 次
fast_delay=0.3, # 快速间隔 0.3s
slow_retries=2, # 慢速重试 2 次
slow_delay_base=5.0, # 慢速起始 5s
retry_on_status=(429, 500, 502, 503),
)
dl = Downloader(workers=5, retry_policy=policy)
进度回调
def on_progress(done, total, result):
status = "OK" if result.success else "FAIL"
print(f"[{done}/{total}] {result.task.url} {status}")
report = dl.run(on_progress=on_progress)
请求前/响应后钩子
from dataclasses import replace
def add_proxy(task):
"""请求前动态设置代理"""
return replace(task, proxies={"https": "http://proxy:8080"})
def check_captcha(result):
"""响应后检测验证码"""
if result.success and "验证码" in (result.text or ""):
result.success = False
result.error = "触发验证码"
return result
dl = Downloader(
workers=5,
before_request=add_proxy,
after_response=check_captcha,
)
上下文管理器
with Downloader(workers=10) as dl:
dl.add_tasks(tasks)
report = dl.run()
# 自动关闭 session
自定义重试判断
policy = RetryPolicy(
retry_on=lambda status, exc, resp: (
status in (429, 503) or
exc is not None or
(resp and "rate limit" in resp.text.lower())
)
)
API 参考
Task
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url |
str | 必填 | 请求 URL |
method |
str | "GET" | HTTP 方法 |
headers |
dict | None | 请求头 |
params |
dict | None | URL 参数 |
data |
Any | None | 请求体(与 json 互斥) |
json |
Any | None | JSON 请求体(与 data 互斥) |
timeout |
float | 10.0 | 超时时间(秒) |
proxies |
dict | None | 代理配置 |
meta |
dict | None | 业务自定义数据,结果中原样带回 |
task_id |
str | 自动生成 | 任务 ID,相同请求生成相同 ID |
Downloader
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
workers |
int | 5 | 线程池大小 |
retry_policy |
RetryPolicy | 默认策略 | 重试策略 |
queue |
BaseQueue | MemoryQueue | 任务队列 |
session |
Session | 自动创建 | requests Session |
before_request |
Callable | None | 请求前钩子 |
after_response |
Callable | None | 响应后钩子 |
DownloadReport
| 属性/方法 | 说明 |
|---|---|
total |
总任务数 |
success_count |
成功数 |
failed_count |
失败数 |
success |
成功的 Result 列表 |
failed |
失败的 Result 列表 |
failed_tasks() |
失败的 Task 列表,可直接重新提交 |
failed_urls() |
失败的 URL 列表 |
summary() |
摘要字符串 |
开发
# 安装开发依赖
pip install -e ".[dev]"
# 运行测试
pytest tests/ -v
# 带覆盖率
pytest tests/ -v --cov=bw_retry_downloader
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
bw_retry_downloader-0.1.0.tar.gz
(13.6 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file bw_retry_downloader-0.1.0.tar.gz.
File metadata
- Download URL: bw_retry_downloader-0.1.0.tar.gz
- Upload date:
- Size: 13.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0359e40eaa14180d81f768b2e9eab784ace0752225b3f58614b4215532058050
|
|
| MD5 |
d40b2f4638516877b285b0798303a9dc
|
|
| BLAKE2b-256 |
e8fecaa843f3b73a77fcdfb508ab5f0711bb93b45387728d94fa297cf9565488
|
File details
Details for the file bw_retry_downloader-0.1.0-py3-none-any.whl.
File metadata
- Download URL: bw_retry_downloader-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6d8a8ff46fef5d26e1e29720e11bdc41676e308db60034ef52b224978aed8356
|
|
| MD5 |
ff53441c63329f992b4ae9c15b14ebbd
|
|
| BLAKE2b-256 |
acb722200e44f805d7ed540d28ca932897eba35db8326feaf863f37454b3b4dc
|