crawlo 1.1.1__py3-none-any.whl → 1.1.2__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 crawlo might be problematic. Click here for more details.
- crawlo/__init__.py +2 -1
- crawlo/__version__.py +1 -1
- crawlo/commands/genspider.py +68 -42
- crawlo/commands/list.py +102 -93
- crawlo/commands/startproject.py +89 -4
- crawlo/commands/utils.py +187 -0
- crawlo/config.py +280 -0
- crawlo/core/engine.py +16 -3
- crawlo/core/enhanced_engine.py +190 -0
- crawlo/core/scheduler.py +113 -8
- crawlo/crawler.py +840 -307
- crawlo/downloader/__init__.py +181 -17
- crawlo/downloader/aiohttp_downloader.py +15 -2
- crawlo/downloader/cffi_downloader.py +11 -1
- crawlo/downloader/httpx_downloader.py +14 -3
- crawlo/filters/__init__.py +122 -5
- crawlo/filters/aioredis_filter.py +128 -36
- crawlo/filters/memory_filter.py +99 -32
- crawlo/middleware/proxy.py +11 -8
- crawlo/middleware/retry.py +40 -5
- crawlo/mode_manager.py +201 -0
- crawlo/network/__init__.py +17 -3
- crawlo/network/request.py +118 -10
- crawlo/network/response.py +131 -28
- crawlo/pipelines/__init__.py +1 -1
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/queue/__init__.py +0 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +304 -0
- crawlo/queue/redis_priority_queue.py +192 -0
- crawlo/settings/default_settings.py +68 -9
- crawlo/spider/__init__.py +576 -66
- crawlo/task_manager.py +4 -1
- crawlo/templates/project/middlewares.py.tmpl +56 -45
- crawlo/templates/project/pipelines.py.tmpl +308 -36
- crawlo/templates/project/run.py.tmpl +239 -0
- crawlo/templates/project/settings.py.tmpl +211 -17
- crawlo/templates/spider/spider.py.tmpl +153 -7
- crawlo/utils/controlled_spider_mixin.py +336 -0
- crawlo/utils/large_scale_config.py +287 -0
- crawlo/utils/large_scale_helper.py +344 -0
- crawlo/utils/queue_helper.py +176 -0
- crawlo/utils/request_serializer.py +220 -0
- crawlo-1.1.2.dist-info/METADATA +567 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
- tests/test_final_validation.py +154 -0
- tests/test_redis_config.py +29 -0
- tests/test_redis_queue.py +225 -0
- tests/test_request_serialization.py +71 -0
- tests/test_scheduler.py +242 -0
- crawlo/pipelines/mysql_batch_pipline.py +0 -273
- crawlo/utils/pqueue.py +0 -174
- crawlo-1.1.1.dist-info/METADATA +0 -220
- examples/baidu_spider/__init__.py +0 -7
- examples/baidu_spider/demo.py +0 -94
- examples/baidu_spider/items.py +0 -46
- examples/baidu_spider/middleware.py +0 -49
- examples/baidu_spider/pipeline.py +0 -55
- examples/baidu_spider/run.py +0 -27
- examples/baidu_spider/settings.py +0 -121
- examples/baidu_spider/spiders/__init__.py +0 -7
- examples/baidu_spider/spiders/bai_du.py +0 -61
- examples/baidu_spider/spiders/miit.py +0 -159
- examples/baidu_spider/spiders/sina.py +0 -79
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
|
@@ -1,27 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/python
|
|
2
2
|
# -*- coding:UTF-8 -*-
|
|
3
|
-
|
|
3
|
+
"""
|
|
4
|
+
Redis 过滤器实现
|
|
5
|
+
=================
|
|
6
|
+
提供基于 Redis 的分布式请求去重功能。
|
|
7
|
+
|
|
8
|
+
特点:
|
|
9
|
+
- 分布式支持: 多节点共享去重数据
|
|
10
|
+
- TTL 支持: 自动过期清理
|
|
11
|
+
- 高性能: 使用 Redis pipeline 优化
|
|
12
|
+
- 容错设计: 网络异常自动重试
|
|
13
|
+
"""
|
|
4
14
|
from typing import Optional
|
|
5
|
-
from
|
|
15
|
+
from redis import asyncio as aioredis
|
|
6
16
|
from crawlo.filters import BaseFilter
|
|
7
17
|
from crawlo.utils.log import get_logger
|
|
8
18
|
from crawlo.utils.request import request_fingerprint
|
|
9
19
|
|
|
10
20
|
|
|
11
21
|
class AioRedisFilter(BaseFilter):
|
|
12
|
-
"""
|
|
22
|
+
"""
|
|
23
|
+
基于Redis集合实现的异步请求去重过滤器
|
|
24
|
+
|
|
25
|
+
支持特性:
|
|
26
|
+
- 分布式爬虫多节点共享去重数据
|
|
27
|
+
- TTL 自动过期清理机制
|
|
28
|
+
- Pipeline 批量操作优化性能
|
|
29
|
+
- 容错设计和连接池管理
|
|
30
|
+
|
|
31
|
+
适用场景:
|
|
32
|
+
- 分布式爬虫系统
|
|
33
|
+
- 大规模数据处理
|
|
34
|
+
- 需要持久化去重的场景
|
|
35
|
+
"""
|
|
13
36
|
|
|
14
37
|
def __init__(
|
|
15
38
|
self,
|
|
16
39
|
redis_key: str,
|
|
17
40
|
client: aioredis.Redis,
|
|
18
41
|
stats: dict,
|
|
19
|
-
debug: bool,
|
|
20
|
-
log_level: str,
|
|
42
|
+
debug: bool = False,
|
|
43
|
+
log_level: str = 'INFO',
|
|
21
44
|
cleanup_fp: bool = False,
|
|
22
45
|
ttl: Optional[int] = None
|
|
23
46
|
):
|
|
24
|
-
"""
|
|
47
|
+
"""
|
|
48
|
+
初始化Redis过滤器
|
|
49
|
+
|
|
50
|
+
:param redis_key: Redis中存储指纹的键名
|
|
51
|
+
:param client: Redis客户端实例
|
|
52
|
+
:param stats: 统计信息存储
|
|
53
|
+
:param debug: 是否启用调试模式
|
|
54
|
+
:param log_level: 日志级别
|
|
55
|
+
:param cleanup_fp: 关闭时是否清理指纹
|
|
56
|
+
:param ttl: 指纹过期时间(秒)
|
|
57
|
+
"""
|
|
25
58
|
self.logger = get_logger(self.__class__.__name__, log_level)
|
|
26
59
|
super().__init__(self.logger, stats, debug)
|
|
27
60
|
|
|
@@ -29,6 +62,10 @@ class AioRedisFilter(BaseFilter):
|
|
|
29
62
|
self.redis = client
|
|
30
63
|
self.cleanup_fp = cleanup_fp
|
|
31
64
|
self.ttl = ttl
|
|
65
|
+
|
|
66
|
+
# 性能计数器
|
|
67
|
+
self._redis_operations = 0
|
|
68
|
+
self._pipeline_operations = 0
|
|
32
69
|
|
|
33
70
|
@classmethod
|
|
34
71
|
def create_instance(cls, crawler) -> 'BaseFilter':
|
|
@@ -62,60 +99,115 @@ class AioRedisFilter(BaseFilter):
|
|
|
62
99
|
log_level=crawler.settings.get('LOG_LEVEL', 'INFO')
|
|
63
100
|
)
|
|
64
101
|
|
|
65
|
-
async def requested(self, request
|
|
66
|
-
"""
|
|
102
|
+
async def requested(self, request) -> bool:
|
|
103
|
+
"""
|
|
104
|
+
检查请求是否已存在(优化版本)
|
|
105
|
+
|
|
106
|
+
:param request: 请求对象
|
|
107
|
+
:return: True 表示重复,False 表示新请求
|
|
108
|
+
"""
|
|
67
109
|
try:
|
|
68
110
|
fp = str(request_fingerprint(request))
|
|
111
|
+
self._redis_operations += 1
|
|
69
112
|
|
|
70
|
-
#
|
|
113
|
+
# 使用 pipeline 优化性能
|
|
71
114
|
pipe = self.redis.pipeline()
|
|
72
|
-
pipe.sismember(self.redis_key, fp)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
115
|
+
pipe.sismember(self.redis_key, fp)
|
|
116
|
+
|
|
117
|
+
results = await pipe.execute()
|
|
118
|
+
exists = results[0]
|
|
119
|
+
|
|
120
|
+
self._pipeline_operations += 1
|
|
121
|
+
|
|
122
|
+
if exists:
|
|
123
|
+
if self.debug:
|
|
124
|
+
self.logger.debug(f"发现重复请求: {fp[:20]}...")
|
|
76
125
|
return True
|
|
77
126
|
|
|
78
|
-
#
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if self.ttl and self.ttl > 0:
|
|
82
|
-
pipe.expire(self.redis_key, self.ttl) # 不单独 await
|
|
83
|
-
await pipe.execute() # 一次性执行所有命令
|
|
84
|
-
|
|
85
|
-
return False # 表示是新请求
|
|
127
|
+
# 如果不存在,添加指纹并设置TTL
|
|
128
|
+
await self.add_fingerprint(fp)
|
|
129
|
+
return False
|
|
86
130
|
|
|
87
131
|
except Exception as e:
|
|
88
|
-
self.logger.error(f"请求检查失败: {getattr(request, 'url', '未知URL')}")
|
|
89
|
-
|
|
132
|
+
self.logger.error(f"请求检查失败: {getattr(request, 'url', '未知URL')} - {e}")
|
|
133
|
+
# 在网络异常时返回False,避免丢失请求
|
|
134
|
+
return False
|
|
90
135
|
|
|
91
136
|
async def add_fingerprint(self, fp: str) -> bool:
|
|
92
|
-
"""
|
|
137
|
+
"""
|
|
138
|
+
添加新指纹到Redis集合(优化版本)
|
|
139
|
+
|
|
140
|
+
:param fp: 请求指纹字符串
|
|
141
|
+
:return: 是否成功添加(True 表示新添加,False 表示已存在)
|
|
142
|
+
"""
|
|
93
143
|
try:
|
|
94
144
|
fp = str(fp)
|
|
95
|
-
|
|
96
|
-
|
|
145
|
+
|
|
146
|
+
# 使用 pipeline 优化性能
|
|
147
|
+
pipe = self.redis.pipeline()
|
|
148
|
+
pipe.sadd(self.redis_key, fp)
|
|
149
|
+
|
|
97
150
|
if self.ttl and self.ttl > 0:
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
151
|
+
pipe.expire(self.redis_key, self.ttl)
|
|
152
|
+
|
|
153
|
+
results = await pipe.execute()
|
|
154
|
+
added = results[0] == 1 # sadd 返回 1 表示新添加
|
|
155
|
+
|
|
156
|
+
self._pipeline_operations += 1
|
|
157
|
+
|
|
158
|
+
if self.debug and added:
|
|
159
|
+
self.logger.debug(f"添加新指纹: {fp[:20]}...")
|
|
160
|
+
|
|
161
|
+
return added
|
|
162
|
+
|
|
101
163
|
except Exception as e:
|
|
102
|
-
self.logger.error("
|
|
103
|
-
|
|
164
|
+
self.logger.error(f"添加指纹失败: {fp[:20]}... - {e}")
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
def __contains__(self, item: str) -> bool:
|
|
168
|
+
"""
|
|
169
|
+
同步版本的包含检查(不推荐在异步环境中使用)
|
|
170
|
+
|
|
171
|
+
:param item: 要检查的指纹
|
|
172
|
+
:return: 是否已存在
|
|
173
|
+
"""
|
|
174
|
+
# 这是一个同步方法,不能直接调用异步Redis操作
|
|
175
|
+
# 建议使用 requested() 方法替代
|
|
176
|
+
raise NotImplementedError("请使用 requested() 方法进行异步检查")
|
|
104
177
|
|
|
105
178
|
async def get_stats(self) -> dict:
|
|
106
|
-
"""
|
|
179
|
+
"""获取过滤器详细统计信息"""
|
|
107
180
|
try:
|
|
108
181
|
count = await self.redis.scard(self.redis_key)
|
|
182
|
+
|
|
183
|
+
# 获取TTL信息
|
|
184
|
+
ttl_info = "TTL未设置"
|
|
185
|
+
if self.ttl:
|
|
186
|
+
remaining_ttl = await self.redis.ttl(self.redis_key)
|
|
187
|
+
if remaining_ttl > 0:
|
|
188
|
+
ttl_info = f"剩余 {remaining_ttl} 秒"
|
|
189
|
+
else:
|
|
190
|
+
ttl_info = f"配置 {self.ttl} 秒"
|
|
191
|
+
|
|
109
192
|
stats = {
|
|
193
|
+
'filter_type': 'AioRedisFilter',
|
|
110
194
|
'指纹总数': count,
|
|
111
195
|
'Redis键名': self.redis_key,
|
|
112
|
-
'TTL配置':
|
|
196
|
+
'TTL配置': ttl_info,
|
|
197
|
+
'Redis操作数': self._redis_operations,
|
|
198
|
+
'Pipeline操作数': self._pipeline_operations,
|
|
199
|
+
'性能优化率': f"{self._pipeline_operations / max(1, self._redis_operations) * 100:.1f}%"
|
|
113
200
|
}
|
|
114
|
-
|
|
201
|
+
|
|
202
|
+
# 合并基类统计
|
|
203
|
+
base_stats = super().get_stats()
|
|
204
|
+
stats.update(base_stats)
|
|
205
|
+
|
|
115
206
|
return stats
|
|
207
|
+
|
|
116
208
|
except Exception as e:
|
|
117
|
-
self.logger.error("
|
|
118
|
-
return
|
|
209
|
+
self.logger.error(f"获取统计信息失败: {e}")
|
|
210
|
+
return super().get_stats()
|
|
119
211
|
|
|
120
212
|
async def clear_all(self) -> int:
|
|
121
213
|
"""清空所有指纹数据"""
|
crawlo/filters/memory_filter.py
CHANGED
|
@@ -1,18 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/python
|
|
2
2
|
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
内存过滤器实现
|
|
5
|
+
================
|
|
6
|
+
提供基于内存的高效请求去重功能。
|
|
7
|
+
|
|
8
|
+
支持的过滤器:
|
|
9
|
+
- MemoryFilter: 纯内存去重,性能最佳
|
|
10
|
+
- MemoryFileFilter: 内存+文件持久化,支持重启恢复
|
|
11
|
+
"""
|
|
3
12
|
import os
|
|
4
13
|
import threading
|
|
5
14
|
from weakref import WeakSet
|
|
6
15
|
from typing import Set, TextIO, Optional
|
|
7
16
|
|
|
8
|
-
from crawlo import Request
|
|
9
17
|
from crawlo.filters import BaseFilter
|
|
10
18
|
from crawlo.utils.log import get_logger
|
|
11
19
|
from crawlo.utils.request import request_fingerprint
|
|
12
20
|
|
|
13
21
|
|
|
14
22
|
class MemoryFilter(BaseFilter):
|
|
15
|
-
"""
|
|
23
|
+
"""
|
|
24
|
+
基于内存的高效请求去重过滤器
|
|
25
|
+
|
|
26
|
+
特点:
|
|
27
|
+
- 高性能: 基于 Python set() 的 O(1) 查找效率
|
|
28
|
+
- 内存优化: 支持弱引用临时存储
|
|
29
|
+
- 统计信息: 提供详细的性能统计
|
|
30
|
+
- 线程安全: 支持多线程并发访问
|
|
31
|
+
|
|
32
|
+
适用场景:
|
|
33
|
+
- 单机爬虫
|
|
34
|
+
- 中小规模数据集
|
|
35
|
+
- 对性能要求较高的场景
|
|
36
|
+
"""
|
|
16
37
|
|
|
17
38
|
def __init__(self, crawler):
|
|
18
39
|
"""
|
|
@@ -21,11 +42,13 @@ class MemoryFilter(BaseFilter):
|
|
|
21
42
|
:param crawler: 爬虫实例,用于获取配置
|
|
22
43
|
"""
|
|
23
44
|
self.fingerprints: Set[str] = set() # 主指纹存储
|
|
24
|
-
self._temp_weak_refs = WeakSet()
|
|
45
|
+
self._temp_weak_refs = WeakSet() # 弱引用临时存储
|
|
46
|
+
self._lock = threading.RLock() # 线程安全锁
|
|
25
47
|
|
|
48
|
+
# 初始化日志和统计
|
|
26
49
|
debug = crawler.settings.get_bool('FILTER_DEBUG', False)
|
|
27
50
|
logger = get_logger(
|
|
28
|
-
self.__class__.__name__,
|
|
51
|
+
self.__class__.__name__,
|
|
29
52
|
crawler.settings.get('LOG_LEVEL', 'INFO')
|
|
30
53
|
)
|
|
31
54
|
super().__init__(logger, crawler.stats, debug)
|
|
@@ -33,10 +56,14 @@ class MemoryFilter(BaseFilter):
|
|
|
33
56
|
# 性能计数器
|
|
34
57
|
self._dupe_count = 0
|
|
35
58
|
self._unique_count = 0
|
|
59
|
+
|
|
60
|
+
# 内存优化配置
|
|
61
|
+
self._max_capacity = crawler.settings.get_int('MEMORY_FILTER_MAX_CAPACITY', 1000000)
|
|
62
|
+
self._cleanup_threshold = crawler.settings.get_float('MEMORY_FILTER_CLEANUP_THRESHOLD', 0.8)
|
|
36
63
|
|
|
37
64
|
def add_fingerprint(self, fp: str) -> None:
|
|
38
65
|
"""
|
|
39
|
-
|
|
66
|
+
线程安全地添加请求指纹
|
|
40
67
|
|
|
41
68
|
:param fp: 请求指纹字符串
|
|
42
69
|
:raises TypeError: 如果指纹不是字符串类型
|
|
@@ -44,56 +71,96 @@ class MemoryFilter(BaseFilter):
|
|
|
44
71
|
if not isinstance(fp, str):
|
|
45
72
|
raise TypeError(f"指纹必须是字符串类型,得到 {type(fp)}")
|
|
46
73
|
|
|
47
|
-
self.
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
74
|
+
with self._lock:
|
|
75
|
+
if fp not in self.fingerprints:
|
|
76
|
+
# 检查容量限制
|
|
77
|
+
if len(self.fingerprints) >= self._max_capacity:
|
|
78
|
+
self._cleanup_old_fingerprints()
|
|
79
|
+
|
|
80
|
+
self.fingerprints.add(fp)
|
|
81
|
+
self._unique_count += 1
|
|
82
|
+
|
|
83
|
+
if self.debug:
|
|
84
|
+
self.logger.debug(f"添加指纹: {fp[:20]}...")
|
|
85
|
+
|
|
86
|
+
def _cleanup_old_fingerprints(self) -> None:
|
|
87
|
+
"""清理老旧指纹释放内存空间"""
|
|
88
|
+
cleanup_count = int(len(self.fingerprints) * (1 - self._cleanup_threshold))
|
|
89
|
+
if cleanup_count > 0:
|
|
90
|
+
# 随机清理一部分指纹(简单策略)
|
|
91
|
+
fingerprints_list = list(self.fingerprints)
|
|
92
|
+
import random
|
|
93
|
+
to_remove = random.sample(fingerprints_list, cleanup_count)
|
|
94
|
+
self.fingerprints.difference_update(to_remove)
|
|
95
|
+
self.logger.info(f"清理了 {cleanup_count} 个老旧指纹")
|
|
96
|
+
|
|
97
|
+
def requested(self, request) -> bool:
|
|
52
98
|
"""
|
|
53
|
-
|
|
99
|
+
线程安全地检查请求是否重复(主要接口)
|
|
54
100
|
|
|
55
101
|
:param request: 请求对象
|
|
56
102
|
:return: 是否重复
|
|
57
103
|
"""
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
self.
|
|
61
|
-
|
|
62
|
-
|
|
104
|
+
with self._lock:
|
|
105
|
+
fp = request_fingerprint(request)
|
|
106
|
+
if fp in self.fingerprints:
|
|
107
|
+
self._dupe_count += 1
|
|
108
|
+
if self.debug:
|
|
109
|
+
self.logger.debug(f"发现重复请求: {fp[:20]}...")
|
|
110
|
+
return True
|
|
63
111
|
|
|
64
|
-
|
|
65
|
-
|
|
112
|
+
self.add_fingerprint(fp)
|
|
113
|
+
return False
|
|
66
114
|
|
|
67
115
|
def __contains__(self, item: str) -> bool:
|
|
68
116
|
"""
|
|
69
|
-
|
|
117
|
+
线程安全地支持 in 操作符检查
|
|
70
118
|
|
|
71
119
|
:param item: 要检查的指纹
|
|
72
120
|
:return: 是否已存在
|
|
73
121
|
"""
|
|
74
|
-
|
|
122
|
+
with self._lock:
|
|
123
|
+
return item in self.fingerprints
|
|
75
124
|
|
|
76
125
|
@property
|
|
77
126
|
def stats_summary(self) -> dict:
|
|
78
127
|
"""获取过滤器统计信息"""
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
128
|
+
with self._lock:
|
|
129
|
+
return {
|
|
130
|
+
'filter_type': 'MemoryFilter',
|
|
131
|
+
'capacity': len(self.fingerprints),
|
|
132
|
+
'max_capacity': self._max_capacity,
|
|
133
|
+
'duplicates': self._dupe_count,
|
|
134
|
+
'uniques': self._unique_count,
|
|
135
|
+
'total_processed': self._dupe_count + self._unique_count,
|
|
136
|
+
'duplicate_rate': f"{self._dupe_count / max(1, self._dupe_count + self._unique_count) * 100:.2f}%",
|
|
137
|
+
'memory_usage': self._estimate_memory(),
|
|
138
|
+
'capacity_usage': f"{len(self.fingerprints) / self._max_capacity * 100:.2f}%"
|
|
139
|
+
}
|
|
85
140
|
|
|
86
141
|
def _estimate_memory(self) -> str:
|
|
87
142
|
"""估算内存使用量(近似值)"""
|
|
88
|
-
|
|
143
|
+
if not self.fingerprints:
|
|
144
|
+
return "0 MB"
|
|
145
|
+
|
|
146
|
+
avg_item_size = sum(len(x) for x in self.fingerprints) / len(self.fingerprints)
|
|
89
147
|
total = len(self.fingerprints) * (avg_item_size + 50) # 50字节额外开销
|
|
90
|
-
|
|
148
|
+
|
|
149
|
+
if total < 1024:
|
|
150
|
+
return f"{total:.1f} B"
|
|
151
|
+
elif total < 1024 * 1024:
|
|
152
|
+
return f"{total / 1024:.1f} KB"
|
|
153
|
+
else:
|
|
154
|
+
return f"{total / (1024 * 1024):.2f} MB"
|
|
91
155
|
|
|
92
156
|
def clear(self) -> None:
|
|
93
|
-
"""
|
|
94
|
-
self.
|
|
95
|
-
|
|
96
|
-
|
|
157
|
+
"""线程安全地清空所有指纹数据"""
|
|
158
|
+
with self._lock:
|
|
159
|
+
self.fingerprints.clear()
|
|
160
|
+
self._dupe_count = 0
|
|
161
|
+
self._unique_count = 0
|
|
162
|
+
if self.debug:
|
|
163
|
+
self.logger.debug("已清空所有指纹")
|
|
97
164
|
|
|
98
165
|
def close(self) -> None:
|
|
99
166
|
"""关闭过滤器(清理资源)"""
|
crawlo/middleware/proxy.py
CHANGED
|
@@ -2,16 +2,18 @@
|
|
|
2
2
|
# -*- coding: UTF-8 -*-
|
|
3
3
|
import asyncio
|
|
4
4
|
import socket
|
|
5
|
-
from typing import Optional, Dict, Any, Callable, Union
|
|
5
|
+
from typing import Optional, Dict, Any, Callable, Union, TYPE_CHECKING
|
|
6
6
|
from urllib.parse import urlparse
|
|
7
7
|
|
|
8
8
|
from crawlo import Request, Response
|
|
9
9
|
from crawlo.exceptions import NotConfiguredError
|
|
10
10
|
from crawlo.utils.log import get_logger
|
|
11
11
|
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import aiohttp
|
|
14
|
+
|
|
12
15
|
try:
|
|
13
16
|
import httpx
|
|
14
|
-
|
|
15
17
|
HTTPX_EXCEPTIONS = (httpx.NetworkError, httpx.TimeoutException, httpx.ReadError, httpx.ConnectError)
|
|
16
18
|
except ImportError:
|
|
17
19
|
HTTPX_EXCEPTIONS = ()
|
|
@@ -19,17 +21,15 @@ except ImportError:
|
|
|
19
21
|
|
|
20
22
|
try:
|
|
21
23
|
import aiohttp
|
|
22
|
-
|
|
23
24
|
AIOHTTP_EXCEPTIONS = (
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
aiohttp.ClientError, aiohttp.ClientConnectorError, aiohttp.ClientResponseError, aiohttp.ServerTimeoutError,
|
|
26
|
+
aiohttp.ServerDisconnectedError)
|
|
26
27
|
except ImportError:
|
|
27
28
|
AIOHTTP_EXCEPTIONS = ()
|
|
28
29
|
aiohttp = None
|
|
29
30
|
|
|
30
31
|
try:
|
|
31
32
|
from curl_cffi import requests as cffi_requests
|
|
32
|
-
|
|
33
33
|
CURL_CFFI_EXCEPTIONS = (cffi_requests.RequestsError,)
|
|
34
34
|
except (ImportError, AttributeError):
|
|
35
35
|
CURL_CFFI_EXCEPTIONS = ()
|
|
@@ -49,7 +49,7 @@ class ProxyMiddleware:
|
|
|
49
49
|
def __init__(self, settings, log_level):
|
|
50
50
|
self.logger = get_logger(self.__class__.__name__, log_level)
|
|
51
51
|
|
|
52
|
-
self._session: Optional[aiohttp.ClientSession
|
|
52
|
+
self._session: Optional[Any] = None # aiohttp.ClientSession when aiohttp is available
|
|
53
53
|
self._current_proxy: Optional[Union[str, Dict[str, str]]] = None
|
|
54
54
|
self._last_fetch_time: float = 0
|
|
55
55
|
|
|
@@ -104,7 +104,10 @@ class ProxyMiddleware:
|
|
|
104
104
|
finally:
|
|
105
105
|
self._session = None
|
|
106
106
|
|
|
107
|
-
async def _get_session(self) -> aiohttp.ClientSession
|
|
107
|
+
async def _get_session(self) -> Any: # returns aiohttp.ClientSession when aiohttp is available
|
|
108
|
+
if aiohttp is None:
|
|
109
|
+
raise RuntimeError("aiohttp 未安装,无法使用 ProxyMiddleware")
|
|
110
|
+
|
|
108
111
|
if self._session is None or self._session.closed:
|
|
109
112
|
if self._session and self._session.closed:
|
|
110
113
|
self.logger.debug("现有 session 已关闭,正在创建新 session...")
|
crawlo/middleware/retry.py
CHANGED
|
@@ -1,12 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/python
|
|
2
2
|
# -*- coding:UTF-8 -*-
|
|
3
3
|
from typing import List
|
|
4
|
-
from anyio import EndOfStream
|
|
5
|
-
from httpcore import ReadError
|
|
6
4
|
from asyncio.exceptions import TimeoutError
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
from
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from anyio import EndOfStream
|
|
8
|
+
except ImportError:
|
|
9
|
+
# 如果 anyio 不可用或者 EndOfStream 不存在,创建一个占位符
|
|
10
|
+
class EndOfStream(Exception):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from httpcore import ReadError
|
|
15
|
+
except ImportError:
|
|
16
|
+
class ReadError(Exception):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from httpx import RemoteProtocolError, ConnectError, ReadTimeout
|
|
21
|
+
except ImportError:
|
|
22
|
+
class RemoteProtocolError(Exception):
|
|
23
|
+
pass
|
|
24
|
+
class ConnectError(Exception):
|
|
25
|
+
pass
|
|
26
|
+
class ReadTimeout(Exception):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from aiohttp.client_exceptions import ClientConnectionError, ClientPayloadError
|
|
31
|
+
from aiohttp import ClientConnectorError, ClientTimeout, ClientConnectorSSLError, ClientResponseError
|
|
32
|
+
except ImportError:
|
|
33
|
+
class ClientConnectionError(Exception):
|
|
34
|
+
pass
|
|
35
|
+
class ClientPayloadError(Exception):
|
|
36
|
+
pass
|
|
37
|
+
class ClientConnectorError(Exception):
|
|
38
|
+
pass
|
|
39
|
+
class ClientTimeout(Exception):
|
|
40
|
+
pass
|
|
41
|
+
class ClientConnectorSSLError(Exception):
|
|
42
|
+
pass
|
|
43
|
+
class ClientResponseError(Exception):
|
|
44
|
+
pass
|
|
10
45
|
|
|
11
46
|
from crawlo.utils.log import get_logger
|
|
12
47
|
from crawlo.stats_collector import StatsCollector
|