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/network/request.py CHANGED
@@ -1,205 +1,204 @@
1
- #!/usr/bin/python
2
- # -*- coding: UTF-8 -*-
3
- import json
4
- from copy import deepcopy
5
- from urllib.parse import urlencode
6
- from w3lib.url import safe_url_string
7
- from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
8
-
9
- from crawlo.utils.url import escape_ajax
10
-
11
-
12
- _Request = TypeVar("_Request", bound="Request")
13
-
14
-
15
- class RequestPriority:
16
- """请求优先级常量"""
17
- HIGH = -100
18
- NORMAL = 0
19
- LOW = 100
20
-
21
-
22
- class Request:
23
- """
24
- 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
25
- 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
26
- 不支持文件上传(multipart/form-data),保持轻量。
27
- """
28
-
29
- __slots__ = (
30
- '_url',
31
- '_meta',
32
- 'callback',
33
- 'cb_kwargs',
34
- 'err_back',
35
- 'headers',
36
- 'body',
37
- 'method',
38
- 'cookies',
39
- 'priority',
40
- 'encoding',
41
- 'dont_filter',
42
- 'timeout',
43
- 'proxy',
44
- 'allow_redirects',
45
- 'auth',
46
- 'verify',
47
- 'flags',
48
- # 保留高层参数用于 copy()
49
- '_json_body',
50
- '_form_data'
51
- )
52
-
53
- def __init__(
54
- self,
55
- url: str,
56
- callback: Optional[Callable] = None,
57
- method: Optional[str] = 'GET',
58
- headers: Optional[Dict[str, str]] = None,
59
- body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
60
- form_data: Optional[Dict[Any, Any]] = None,
61
- json_body: Optional[Dict[Any, Any]] = None,
62
- cb_kwargs: Optional[Dict[str, Any]] = None,
63
- cookies: Optional[Dict[str, str]] = None,
64
- meta: Optional[Dict[str, Any]] = None,
65
- priority: int = RequestPriority.NORMAL,
66
- dont_filter: bool = False,
67
- timeout: Optional[float] = None,
68
- proxy: Optional[str] = None,
69
- allow_redirects: bool = True,
70
- auth: Optional[tuple] = None,
71
- verify: bool = True,
72
- flags: Optional[List[str]] = None,
73
- encoding: str = 'utf-8'
74
- ):
75
- """
76
- 初始化请求对象。
77
-
78
- :param url: 请求 URL(必须)
79
- :param callback: 成功回调函数
80
- :param method: HTTP 方法,默认 GET
81
- :param headers: 请求头
82
- :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
83
- :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
84
- :param json_body: JSON 数据,自动序列化并设置 Content-Type
85
- :param cb_kwargs: 传递给 callback 的额外参数
86
- :param cookies: Cookies 字典
87
- :param meta: 元数据(跨中间件传递数据)
88
- :param priority: 优先级(数值越小越优先)
89
- :param dont_filter: 是否跳过去重
90
- :param timeout: 超时时间(秒)
91
- :param proxy: 代理地址,如 http://127.0.0.1:8080
92
- :param allow_redirects: 是否允许重定向
93
- :param auth: 认证元组 (username, password)
94
- :param verify: 是否验证 SSL 证书
95
- :param flags: 标记(用于调试或分类)
96
- :param encoding: 字符编码,默认 utf-8
97
- """
98
- self.callback = callback
99
- self.method = str(method).upper()
100
- self.headers = headers or {}
101
- self.cookies = cookies or {}
102
- self.priority = -priority # 用于排序:值越小优先级越高
103
- self._meta = deepcopy(meta) if meta is not None else {}
104
- self.timeout = self._meta.get('download_timeout', timeout)
105
- self.proxy = proxy
106
- self.allow_redirects = allow_redirects
107
- self.auth = auth
108
- self.verify = verify
109
- self.flags = flags or []
110
- self.encoding = encoding
111
- self.cb_kwargs = cb_kwargs or {}
112
- self.body = body
113
- # 保存高层语义参数(用于 copy)
114
- self._json_body = json_body
115
- self._form_data = form_data
116
-
117
- # 构建 body
118
- if json_body is not None:
119
- if 'Content-Type' not in self.headers:
120
- self.headers['Content-Type'] = 'application/json'
121
- self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
122
- if self.method == 'GET':
123
- self.method = 'POST'
124
-
125
- elif form_data is not None:
126
- if self.method == 'GET':
127
- self.method = 'POST'
128
- if 'Content-Type' not in self.headers:
129
- self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
130
- query_str = urlencode(form_data)
131
- self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
132
-
133
-
134
- else:
135
- # 处理原始 body
136
- if isinstance(self.body, dict):
137
- if 'Content-Type' not in self.headers:
138
- self.headers['Content-Type'] = 'application/json'
139
- self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
140
- elif isinstance(self.body, str):
141
- self.body = self.body.encode(encoding)
142
-
143
- self.dont_filter = dont_filter
144
- self._set_url(url)
145
-
146
- def copy(self: _Request) -> _Request:
147
- """
148
- 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
149
- """
150
- return type(self)(
151
- url=self.url,
152
- callback=self.callback,
153
- method=self.method,
154
- headers=self.headers.copy(),
155
- body=None, # 由 form_data/json_body 重新生成
156
- form_data=self._form_data,
157
- json_body=self._json_body,
158
- cb_kwargs=deepcopy(self.cb_kwargs),
159
- err_back=self.err_back,
160
- cookies=self.cookies.copy(),
161
- meta=deepcopy(self._meta),
162
- priority=-self.priority,
163
- dont_filter=self.dont_filter,
164
- timeout=self.timeout,
165
- proxy=self.proxy,
166
- allow_redirects=self.allow_redirects,
167
- auth=self.auth,
168
- verify=self.verify,
169
- flags=self.flags.copy(),
170
- encoding=self.encoding
171
- )
172
-
173
- def set_meta(self, key: str, value: Any) -> None:
174
- """设置 meta 中的某个键值。"""
175
- self._meta[key] = value
176
-
177
- def _set_url(self, url: str) -> None:
178
- """安全设置 URL,确保格式正确。"""
179
- if not isinstance(url, str):
180
- raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
181
-
182
- s = safe_url_string(url, self.encoding)
183
- escaped_url = escape_ajax(s)
184
- self._url = escaped_url
185
-
186
- if not self._url.startswith(('http://', 'https://')):
187
- raise ValueError(f"URL 缺少 scheme: {self._url}")
188
-
189
- @property
190
- def url(self) -> str:
191
- return self._url
192
-
193
- @property
194
- def meta(self) -> Dict[str, Any]:
195
- return self._meta
196
-
197
- def __str__(self) -> str:
198
- return f'<Request url={self.url} method={self.method}>'
199
-
200
- def __repr__(self) -> str:
201
- return str(self)
202
-
203
- def __lt__(self, other: _Request) -> bool:
204
- """用于按优先级排序"""
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ import json
4
+ from copy import deepcopy
5
+ from urllib.parse import urlencode
6
+ from w3lib.url import safe_url_string
7
+ from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
8
+
9
+ from crawlo.utils.url import escape_ajax
10
+
11
+
12
+ _Request = TypeVar("_Request", bound="Request")
13
+
14
+
15
+ class RequestPriority:
16
+ """请求优先级常量"""
17
+ HIGH = -100
18
+ NORMAL = 0
19
+ LOW = 100
20
+
21
+
22
+ class Request:
23
+ """
24
+ 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
25
+ 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
26
+ 不支持文件上传(multipart/form-data),保持轻量。
27
+ """
28
+
29
+ __slots__ = (
30
+ '_url',
31
+ '_meta',
32
+ 'callback',
33
+ 'cb_kwargs',
34
+ 'err_back',
35
+ 'headers',
36
+ 'body',
37
+ 'method',
38
+ 'cookies',
39
+ 'priority',
40
+ 'encoding',
41
+ 'dont_filter',
42
+ 'timeout',
43
+ 'proxy',
44
+ 'allow_redirects',
45
+ 'auth',
46
+ 'verify',
47
+ 'flags',
48
+ '_json_body',
49
+ '_form_data'
50
+ )
51
+
52
+ def __init__(
53
+ self,
54
+ url: str,
55
+ callback: Optional[Callable] = None,
56
+ method: Optional[str] = 'GET',
57
+ headers: Optional[Dict[str, str]] = None,
58
+ body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
59
+ form_data: Optional[Dict[Any, Any]] = None,
60
+ json_body: Optional[Dict[Any, Any]] = None,
61
+ cb_kwargs: Optional[Dict[str, Any]] = None,
62
+ cookies: Optional[Dict[str, str]] = None,
63
+ meta: Optional[Dict[str, Any]] = None,
64
+ priority: int = RequestPriority.NORMAL,
65
+ dont_filter: bool = False,
66
+ timeout: Optional[float] = None,
67
+ proxy: Optional[str] = None,
68
+ allow_redirects: bool = True,
69
+ auth: Optional[tuple] = None,
70
+ verify: bool = True,
71
+ flags: Optional[List[str]] = None,
72
+ encoding: str = 'utf-8'
73
+ ):
74
+ """
75
+ 初始化请求对象。
76
+
77
+ :param url: 请求 URL(必须)
78
+ :param callback: 成功回调函数
79
+ :param method: HTTP 方法,默认 GET
80
+ :param headers: 请求头
81
+ :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
82
+ :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
83
+ :param json_body: JSON 数据,自动序列化并设置 Content-Type
84
+ :param cb_kwargs: 传递给 callback 的额外参数
85
+ :param cookies: Cookies 字典
86
+ :param meta: 元数据(跨中间件传递数据)
87
+ :param priority: 优先级(数值越小越优先)
88
+ :param dont_filter: 是否跳过去重
89
+ :param timeout: 超时时间(秒)
90
+ :param proxy: 代理地址,如 http://127.0.0.1:8080
91
+ :param allow_redirects: 是否允许重定向
92
+ :param auth: 认证元组 (username, password)
93
+ :param verify: 是否验证 SSL 证书
94
+ :param flags: 标记(用于调试或分类)
95
+ :param encoding: 字符编码,默认 utf-8
96
+ """
97
+ self.callback = callback
98
+ self.method = str(method).upper()
99
+ self.headers = headers or {}
100
+ self.cookies = cookies or {}
101
+ self.priority = -priority # 用于排序:值越小优先级越高
102
+ self._meta = deepcopy(meta) if meta is not None else {}
103
+ self.timeout = self._meta.get('download_timeout', timeout)
104
+ self.proxy = proxy
105
+ self.allow_redirects = allow_redirects
106
+ self.auth = auth
107
+ self.verify = verify
108
+ self.flags = flags or []
109
+ self.encoding = encoding
110
+ self.cb_kwargs = cb_kwargs or {}
111
+ self.body = body
112
+ # 保存高层语义参数(用于 copy)
113
+ self._json_body = json_body
114
+ self._form_data = form_data
115
+
116
+ # 构建 body
117
+ if json_body is not None:
118
+ if 'Content-Type' not in self.headers:
119
+ self.headers['Content-Type'] = 'application/json'
120
+ self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
121
+ if self.method == 'GET':
122
+ self.method = 'POST'
123
+
124
+ elif form_data is not None:
125
+ if self.method == 'GET':
126
+ self.method = 'POST'
127
+ if 'Content-Type' not in self.headers:
128
+ self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
129
+ query_str = urlencode(form_data)
130
+ self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
131
+
132
+
133
+ else:
134
+ # 处理原始 body
135
+ if isinstance(self.body, dict):
136
+ if 'Content-Type' not in self.headers:
137
+ self.headers['Content-Type'] = 'application/json'
138
+ self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
139
+ elif isinstance(self.body, str):
140
+ self.body = self.body.encode(encoding)
141
+
142
+ self.dont_filter = dont_filter
143
+ self._set_url(url)
144
+
145
+ def copy(self: _Request) -> _Request:
146
+ """
147
+ 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
148
+ """
149
+ return type(self)(
150
+ url=self.url,
151
+ callback=self.callback,
152
+ method=self.method,
153
+ headers=self.headers.copy(),
154
+ body=None, # 由 form_data/json_body 重新生成
155
+ form_data=self._form_data,
156
+ json_body=self._json_body,
157
+ cb_kwargs=deepcopy(self.cb_kwargs),
158
+ err_back=self.err_back,
159
+ cookies=self.cookies.copy(),
160
+ meta=deepcopy(self._meta),
161
+ priority=-self.priority,
162
+ dont_filter=self.dont_filter,
163
+ timeout=self.timeout,
164
+ proxy=self.proxy,
165
+ allow_redirects=self.allow_redirects,
166
+ auth=self.auth,
167
+ verify=self.verify,
168
+ flags=self.flags.copy(),
169
+ encoding=self.encoding
170
+ )
171
+
172
+ def set_meta(self, key: str, value: Any) -> None:
173
+ """设置 meta 中的某个键值。"""
174
+ self._meta[key] = value
175
+
176
+ def _set_url(self, url: str) -> None:
177
+ """安全设置 URL,确保格式正确。"""
178
+ if not isinstance(url, str):
179
+ raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
180
+
181
+ s = safe_url_string(url, self.encoding)
182
+ escaped_url = escape_ajax(s)
183
+ self._url = escaped_url
184
+
185
+ if not self._url.startswith(('http://', 'https://')):
186
+ raise ValueError(f"URL 缺少 scheme: {self._url}")
187
+
188
+ @property
189
+ def url(self) -> str:
190
+ return self._url
191
+
192
+ @property
193
+ def meta(self) -> Dict[str, Any]:
194
+ return self._meta
195
+
196
+ def __str__(self) -> str:
197
+ return f'<Request url={self.url} method={self.method}>'
198
+
199
+ def __repr__(self) -> str:
200
+ return str(self)
201
+
202
+ def __lt__(self, other: _Request) -> bool:
203
+ """用于按优先级排序"""
205
204
  return self.priority < other.priority