crawlo 1.0.3__py3-none-any.whl → 1.0.5__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.

Files changed (96) hide show
  1. crawlo/__init__.py +25 -9
  2. crawlo/__version__.py +1 -1
  3. crawlo/core/__init__.py +2 -2
  4. crawlo/core/engine.py +158 -158
  5. crawlo/core/processor.py +40 -40
  6. crawlo/core/scheduler.py +57 -57
  7. crawlo/crawler.py +424 -242
  8. crawlo/downloader/__init__.py +78 -78
  9. crawlo/downloader/aiohttp_downloader.py +200 -259
  10. crawlo/downloader/cffi_downloader.py +277 -0
  11. crawlo/downloader/httpx_downloader.py +246 -187
  12. crawlo/event.py +11 -11
  13. crawlo/exceptions.py +73 -64
  14. crawlo/extension/__init__.py +31 -31
  15. crawlo/extension/log_interval.py +49 -49
  16. crawlo/extension/log_stats.py +44 -44
  17. crawlo/extension/logging_extension.py +35 -0
  18. crawlo/filters/__init__.py +37 -37
  19. crawlo/filters/aioredis_filter.py +150 -158
  20. crawlo/filters/memory_filter.py +202 -202
  21. crawlo/items/__init__.py +62 -62
  22. crawlo/items/items.py +115 -119
  23. crawlo/middleware/__init__.py +21 -21
  24. crawlo/middleware/default_header.py +32 -32
  25. crawlo/middleware/download_delay.py +28 -28
  26. crawlo/middleware/middleware_manager.py +135 -140
  27. crawlo/middleware/proxy.py +246 -0
  28. crawlo/middleware/request_ignore.py +30 -30
  29. crawlo/middleware/response_code.py +18 -18
  30. crawlo/middleware/response_filter.py +26 -26
  31. crawlo/middleware/retry.py +90 -90
  32. crawlo/network/__init__.py +7 -7
  33. crawlo/network/request.py +203 -204
  34. crawlo/network/response.py +166 -166
  35. crawlo/pipelines/__init__.py +13 -13
  36. crawlo/pipelines/console_pipeline.py +39 -39
  37. crawlo/pipelines/mongo_pipeline.py +116 -116
  38. crawlo/pipelines/mysql_batch_pipline.py +273 -134
  39. crawlo/pipelines/mysql_pipeline.py +195 -195
  40. crawlo/pipelines/pipeline_manager.py +56 -56
  41. crawlo/settings/__init__.py +7 -7
  42. crawlo/settings/default_settings.py +169 -93
  43. crawlo/settings/setting_manager.py +99 -99
  44. crawlo/spider/__init__.py +41 -36
  45. crawlo/stats_collector.py +59 -59
  46. crawlo/subscriber.py +106 -106
  47. crawlo/task_manager.py +27 -27
  48. crawlo/templates/item_template.tmpl +21 -21
  49. crawlo/templates/project_template/main.py +32 -32
  50. crawlo/templates/project_template/setting.py +189 -189
  51. crawlo/templates/spider_template.tmpl +30 -30
  52. crawlo/utils/__init__.py +7 -7
  53. crawlo/utils/concurrency_manager.py +124 -124
  54. crawlo/utils/date_tools.py +233 -177
  55. crawlo/utils/db_helper.py +344 -0
  56. crawlo/utils/func_tools.py +82 -82
  57. crawlo/utils/log.py +129 -39
  58. crawlo/utils/pqueue.py +173 -173
  59. crawlo/utils/project.py +59 -59
  60. crawlo/utils/request.py +267 -122
  61. crawlo/utils/system.py +11 -11
  62. crawlo/utils/tools.py +5 -303
  63. crawlo/utils/url.py +39 -39
  64. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/METADATA +49 -48
  65. crawlo-1.0.5.dist-info/RECORD +84 -0
  66. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/top_level.txt +1 -0
  67. examples/__init__.py +0 -0
  68. examples/gxb/__init__.py +0 -0
  69. examples/gxb/items.py +36 -0
  70. examples/gxb/run.py +15 -0
  71. examples/gxb/settings.py +71 -0
  72. examples/gxb/spider/__init__.py +0 -0
  73. examples/gxb/spider/miit_spider.py +180 -0
  74. examples/gxb/spider/telecom_device_licenses.py +129 -0
  75. tests/__init__.py +7 -7
  76. tests/test_proxy_health_check.py +33 -0
  77. tests/test_proxy_middleware_integration.py +137 -0
  78. tests/test_proxy_providers.py +57 -0
  79. tests/test_proxy_stats.py +20 -0
  80. tests/test_proxy_strategies.py +60 -0
  81. crawlo/downloader/playwright_downloader.py +0 -161
  82. crawlo/filters/redis_filter.py +0 -120
  83. crawlo-1.0.3.dist-info/RECORD +0 -80
  84. tests/baidu_spider/__init__.py +0 -7
  85. tests/baidu_spider/demo.py +0 -94
  86. tests/baidu_spider/items.py +0 -25
  87. tests/baidu_spider/middleware.py +0 -49
  88. tests/baidu_spider/pipeline.py +0 -55
  89. tests/baidu_spider/request_fingerprints.txt +0 -9
  90. tests/baidu_spider/run.py +0 -27
  91. tests/baidu_spider/settings.py +0 -78
  92. tests/baidu_spider/spiders/__init__.py +0 -7
  93. tests/baidu_spider/spiders/bai_du.py +0 -61
  94. tests/baidu_spider/spiders/sina.py +0 -79
  95. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/WHEEL +0 -0
  96. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/entry_points.txt +0 -0
crawlo/utils/request.py CHANGED
@@ -1,122 +1,267 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- # @Time : 2025-07-08 08:55
5
- # @Author : crawl-coder
6
- # @Desc : None
7
- """
8
- import json
9
- import hashlib
10
- from typing import Any, Optional, Iterable, Union
11
- from w3lib.url import canonicalize_url
12
-
13
- from crawlo import Request
14
-
15
-
16
- def to_bytes(data: Any, encoding: str = 'utf-8') -> bytes:
17
- """
18
- 将各种类型统一转换为 bytes。
19
-
20
- Args:
21
- data: 要转换的数据,支持 str, bytes, dict, int, float, bool, None 等类型
22
- encoding: 字符串编码格式,默认为 'utf-8'
23
-
24
- Returns:
25
- bytes: 转换后的字节数据
26
-
27
- Raises:
28
- TypeError: 当数据类型无法转换时
29
- UnicodeEncodeError: 当编码失败时
30
- ValueError: 当 JSON 序列化失败时
31
-
32
- Examples:
33
- >>> to_bytes("hello")
34
- b'hello'
35
- >>> to_bytes({"key": "value"})
36
- b'{"key": "value"}'
37
- >>> to_bytes(123)
38
- b'123'
39
- >>> to_bytes(None)
40
- b'null'
41
- """
42
- # 预检查编码参数
43
- if not isinstance(encoding, str):
44
- raise TypeError(f"encoding must be str, not {type(encoding).__name__}")
45
-
46
- try:
47
- if isinstance(data, bytes):
48
- return data
49
- elif isinstance(data, str):
50
- return data.encode(encoding)
51
- elif isinstance(data, dict):
52
- return json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode(encoding)
53
- elif isinstance(data, (int, float, bool)):
54
- return str(data).encode(encoding)
55
- elif data is None:
56
- return b'null'
57
- elif hasattr(data, '__str__'):
58
- # 处理其他可转换为字符串的对象
59
- return str(data).encode(encoding)
60
- else:
61
- raise TypeError(
62
- f"`data` must be str, dict, bytes, int, float, bool, or None, "
63
- f"not {type(data).__name__}"
64
- )
65
- except (UnicodeEncodeError, ValueError) as e:
66
- raise type(e)(f"Failed to convert {type(data).__name__} to bytes: {str(e)}") from e
67
-
68
-
69
- def request_fingerprint(
70
- request: Request,
71
- include_headers: Optional[Iterable[Union[bytes, str]]] = None
72
- ) -> str:
73
- """
74
- 生成请求指纹,基于方法、标准化 URL、body 和可选的 headers。
75
- 使用 SHA256 哈希算法以提高安全性。
76
-
77
- :param request: Request 对象(需包含 method, url, body, headers)
78
- :param include_headers: 指定要参与指纹计算的 header 名称列表(str bytes
79
- :return: 请求指纹(hex string
80
- """
81
- hash_func = hashlib.sha256()
82
-
83
- # 基本字段
84
- hash_func.update(to_bytes(request.method))
85
- hash_func.update(to_bytes(canonicalize_url(request.url)))
86
- hash_func.update(request.body or b'')
87
-
88
- # 处理 headers
89
- if include_headers:
90
- headers = request.headers # 假设 headers 是类似字典或 MultiDict 的结构
91
- for header_name in include_headers:
92
- name_bytes = to_bytes(header_name).lower() # 统一转为小写进行匹配
93
- value = b''
94
-
95
- # 兼容 headers 的访问方式(如 MultiDict 或 dict)
96
- if hasattr(headers, 'get_all'):
97
- # scrapy.http.Headers 的 get_all 方法
98
- values = headers.get_all(name_bytes)
99
- value = b';'.join(values) if values else b''
100
- elif hasattr(headers, '__getitem__'):
101
- # 如普通 dict
102
- try:
103
- raw_value = headers[name_bytes]
104
- if isinstance(raw_value, list):
105
- value = b';'.join(to_bytes(v) for v in raw_value)
106
- else:
107
- value = to_bytes(raw_value)
108
- except (KeyError, TypeError):
109
- value = b''
110
- else:
111
- value = b''
112
-
113
- hash_func.update(name_bytes + b':' + value)
114
-
115
- return hash_func.hexdigest()
116
-
117
-
118
- def set_request(request: Request, priority: int) -> None:
119
- request.meta['depth'] = request.meta.setdefault('depth', 0) + 1
120
- if priority:
121
- request.priority -= request.meta['depth'] * priority
122
-
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ # @Time : 2025-07-08 08:55
5
+ # @Author : crawl-coder
6
+ # @Desc : None
7
+ """
8
+ import importlib
9
+ import json
10
+ import hashlib
11
+ from typing import Any, Optional, Iterable, Union, Dict
12
+ from w3lib.url import canonicalize_url
13
+
14
+ from crawlo import Request
15
+
16
+
17
+ def to_bytes(data: Any, encoding: str = 'utf-8') -> bytes:
18
+ """
19
+ 将各种类型统一转换为 bytes。
20
+
21
+ Args:
22
+ data: 要转换的数据,支持 str, bytes, dict, int, float, bool, None 等类型
23
+ encoding: 字符串编码格式,默认为 'utf-8'
24
+
25
+ Returns:
26
+ bytes: 转换后的字节数据
27
+
28
+ Raises:
29
+ TypeError: 当数据类型无法转换时
30
+ UnicodeEncodeError: 当编码失败时
31
+ ValueError: 当 JSON 序列化失败时
32
+
33
+ Examples:
34
+ >>> to_bytes("hello")
35
+ b'hello'
36
+ >>> to_bytes({"key": "value"})
37
+ b'{"key": "value"}'
38
+ >>> to_bytes(123)
39
+ b'123'
40
+ >>> to_bytes(None)
41
+ b'null'
42
+ """
43
+ # 预检查编码参数
44
+ if not isinstance(encoding, str):
45
+ raise TypeError(f"encoding must be str, not {type(encoding).__name__}")
46
+
47
+ try:
48
+ if isinstance(data, bytes):
49
+ return data
50
+ elif isinstance(data, str):
51
+ return data.encode(encoding)
52
+ elif isinstance(data, dict):
53
+ return json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode(encoding)
54
+ elif isinstance(data, (int, float, bool)):
55
+ return str(data).encode(encoding)
56
+ elif data is None:
57
+ return b'null'
58
+ elif hasattr(data, '__str__'):
59
+ # 处理其他可转换为字符串的对象
60
+ return str(data).encode(encoding)
61
+ else:
62
+ raise TypeError(
63
+ f"`data` must be str, dict, bytes, int, float, bool, or None, "
64
+ f"not {type(data).__name__}"
65
+ )
66
+ except (UnicodeEncodeError, ValueError) as e:
67
+ raise type(e)(f"Failed to convert {type(data).__name__} to bytes: {str(e)}") from e
68
+
69
+
70
+ def request_fingerprint(
71
+ request: Request,
72
+ include_headers: Optional[Iterable[Union[bytes, str]]] = None
73
+ ) -> str:
74
+ """
75
+ 生成请求指纹,基于方法、标准化 URL、body 和可选的 headers。
76
+ 使用 SHA256 哈希算法以提高安全性。
77
+
78
+ :param request: Request 对象(需包含 method, url, body, headers
79
+ :param include_headers: 指定要参与指纹计算的 header 名称列表(str 或 bytes
80
+ :return: 请求指纹(hex string)
81
+ """
82
+ hash_func = hashlib.sha256()
83
+
84
+ # 基本字段
85
+ hash_func.update(to_bytes(request.method))
86
+ hash_func.update(to_bytes(canonicalize_url(request.url)))
87
+ hash_func.update(request.body or b'')
88
+
89
+ # 处理 headers
90
+ if include_headers:
91
+ headers = request.headers # 假设 headers 是类似字典或 MultiDict 的结构
92
+ for header_name in include_headers:
93
+ name_bytes = to_bytes(header_name).lower() # 统一转为小写进行匹配
94
+ value = b''
95
+
96
+ # 兼容 headers 的访问方式(如 MultiDict 或 dict)
97
+ if hasattr(headers, 'get_all'):
98
+ # scrapy.http.Headers 的 get_all 方法
99
+ values = headers.get_all(name_bytes)
100
+ value = b';'.join(values) if values else b''
101
+ elif hasattr(headers, '__getitem__'):
102
+ # 如普通 dict
103
+ try:
104
+ raw_value = headers[name_bytes]
105
+ if isinstance(raw_value, list):
106
+ value = b';'.join(to_bytes(v) for v in raw_value)
107
+ else:
108
+ value = to_bytes(raw_value)
109
+ except (KeyError, TypeError):
110
+ value = b''
111
+ else:
112
+ value = b''
113
+
114
+ hash_func.update(name_bytes + b':' + value)
115
+
116
+ return hash_func.hexdigest()
117
+
118
+
119
+ def set_request(request: Request, priority: int) -> None:
120
+ request.meta['depth'] = request.meta.setdefault('depth', 0) + 1
121
+ if priority:
122
+ request.priority -= request.meta['depth'] * priority
123
+
124
+
125
+ def request_to_dict(request: Request, spider=None) -> Dict[str, Any]:
126
+ """
127
+ 将 Request 对象转换为可 JSON 序列化的字典。
128
+
129
+ Args:
130
+ request: 要序列化的 Request 对象
131
+ spider: 可选,用于辅助序列化(如回调函数的归属)
132
+
133
+ Returns:
134
+ 包含 Request 所有关键信息的字典
135
+ """
136
+ # 基础属性
137
+ d = {
138
+ 'url': request.url,
139
+ 'method': request.method,
140
+ 'headers': dict(request.headers),
141
+ 'body': request.body,
142
+ 'meta': request.meta.copy(), # 复制一份
143
+ 'flags': request.flags.copy(),
144
+ 'cb_kwargs': request.cb_kwargs.copy(),
145
+ }
146
+
147
+ # 1. 处理 callback
148
+ # 不能直接序列化函数,所以存储其路径
149
+ if callable(request.callback):
150
+ d['_callback'] = _get_function_path(request.callback)
151
+
152
+ # 2. 处理 errback
153
+ if callable(request.errback):
154
+ d['_errback'] = _get_function_path(request.errback)
155
+
156
+ # 3. 记录原始类名,以便反序列化时创建正确的实例
157
+ d['_class'] = request.__class__.__module__ + '.' + request.__class__.__name__
158
+
159
+ # 4. 特殊处理 FormRequest
160
+ # 如果是 FormRequest,需要保存 formdata
161
+ if isinstance(request, Request):
162
+ if hasattr(request, 'formdata'):
163
+ d['formdata'] = request.formdata
164
+
165
+ return d
166
+
167
+
168
+ def request_from_dict(d: Dict[str, Any], spider=None) -> Request:
169
+ """
170
+ 从字典重建 Request 对象。
171
+
172
+ Args:
173
+ d: 由 request_to_dict 生成的字典
174
+ spider: 可选,用于解析回调函数
175
+
176
+ Returns:
177
+ 重建的 Request 对象
178
+ """
179
+ # 1. 获取类名并动态导入
180
+ cls_path = d.pop('_class', None)
181
+ if cls_path:
182
+ module_path, cls_name = cls_path.rsplit('.', 1)
183
+ module = importlib.import_module(module_path)
184
+ cls = getattr(module, cls_name)
185
+ else:
186
+ cls = Request # 默认为 Request
187
+
188
+ # 2. 提取回调函数
189
+ callback_path = d.pop('_callback', None)
190
+ callback = _get_function_from_path(callback_path, spider) if callback_path else None
191
+
192
+ # 3. 提取错误回调
193
+ errback_path = d.pop('_errback', None)
194
+ errback = _get_function_from_path(errback_path, spider) if errback_path else None
195
+
196
+ # 4. 提取特殊字段
197
+ formdata = d.pop('formdata', None)
198
+
199
+ # 5. 创建 Request 实例
200
+ # 注意:body 和 formdata 不能同时存在
201
+ if formdata is not None and cls is FormRequest:
202
+ # 如果是 FormRequest 且有 formdata,优先使用 formdata
203
+ request = FormRequest(
204
+ url=d['url'],
205
+ method=d.get('method', 'GET'),
206
+ headers=d.get('headers', {}),
207
+ formdata=formdata,
208
+ callback=callback,
209
+ errback=errback,
210
+ meta=d.get('meta', {}),
211
+ flags=d.get('flags', []),
212
+ cb_kwargs=d.get('cb_kwargs', {}),
213
+ )
214
+ else:
215
+ # 普通 Request 或没有 formdata 的情况
216
+ request = cls(
217
+ url=d['url'],
218
+ method=d.get('method', 'GET'),
219
+ headers=d.get('headers', {}),
220
+ body=d.get('body'),
221
+ callback=callback,
222
+ errback=errback,
223
+ meta=d.get('meta', {}),
224
+ flags=d.get('flags', []),
225
+ cb_kwargs=d.get('cb_kwargs', {}),
226
+ )
227
+
228
+ return request
229
+
230
+
231
+ def _get_function_path(func: callable) -> str:
232
+ """
233
+ 获取函数的模块路径,如 'myproject.spiders.my_spider.parse'
234
+ """
235
+ if hasattr(func, '__wrapped__'):
236
+ # 处理被装饰的函数
237
+ func = func.__wrapped__
238
+ module = func.__module__
239
+ if module is None or module == str.__class__.__module__:
240
+ raise ValueError(f"无法序列化内置函数或lambda: {func}")
241
+ return f"{module}.{func.__qualname__}"
242
+
243
+
244
+ def _get_function_from_path(path: str, spider=None) -> Optional[callable]:
245
+ """
246
+ 从路径字符串获取函数对象。
247
+ 如果函数是 spider 的方法,会尝试绑定到 spider 实例。
248
+ """
249
+ try:
250
+ module_path, func_name = path.rsplit('.', 1)
251
+ module = importlib.import_module(module_path)
252
+
253
+ # 逐级获取属性,支持 nested functions
254
+ func = module
255
+ for attr in func_name.split('.'):
256
+ func = getattr(func, attr)
257
+
258
+ # 如果 spider 存在,并且 func 是 spider 的方法
259
+ if spider and hasattr(spider, func.__name__):
260
+ spider_method = getattr(spider, func.__name__)
261
+ if spider_method is func:
262
+ return spider_method # 返回绑定的方法
263
+
264
+ return func
265
+ except Exception as e:
266
+ raise ValueError(f"无法从路径 '{path}' 加载函数: {e}")
267
+
crawlo/utils/system.py CHANGED
@@ -1,11 +1,11 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- import platform
4
-
5
- system_name = platform.system().lower()
6
- if system_name == 'windows':
7
- import asyncio
8
- asyncio.set_event_loop_policy(
9
- asyncio.WindowsSelectorEventLoopPolicy()
10
- )
11
-
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ import platform
4
+
5
+ system_name = platform.system().lower()
6
+ if system_name == 'windows':
7
+ import asyncio
8
+ asyncio.set_event_loop_policy(
9
+ asyncio.WindowsSelectorEventLoopPolicy()
10
+ )
11
+