crawlo 1.0.1__py3-none-any.whl → 1.0.3__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 (80) hide show
  1. crawlo/__init__.py +9 -6
  2. crawlo/__version__.py +1 -2
  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 -59
  7. crawlo/crawler.py +242 -107
  8. crawlo/downloader/__init__.py +78 -78
  9. crawlo/downloader/aiohttp_downloader.py +259 -96
  10. crawlo/downloader/httpx_downloader.py +187 -48
  11. crawlo/downloader/playwright_downloader.py +160 -160
  12. crawlo/event.py +11 -11
  13. crawlo/exceptions.py +64 -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/filters/__init__.py +37 -37
  18. crawlo/filters/aioredis_filter.py +157 -129
  19. crawlo/filters/memory_filter.py +202 -203
  20. crawlo/filters/redis_filter.py +119 -119
  21. crawlo/items/__init__.py +62 -62
  22. crawlo/items/items.py +118 -118
  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 +140 -140
  27. crawlo/middleware/request_ignore.py +30 -30
  28. crawlo/middleware/response_code.py +18 -18
  29. crawlo/middleware/response_filter.py +26 -26
  30. crawlo/middleware/retry.py +90 -89
  31. crawlo/network/__init__.py +7 -7
  32. crawlo/network/request.py +205 -155
  33. crawlo/network/response.py +166 -93
  34. crawlo/pipelines/__init__.py +13 -13
  35. crawlo/pipelines/console_pipeline.py +39 -39
  36. crawlo/pipelines/mongo_pipeline.py +116 -116
  37. crawlo/pipelines/mysql_batch_pipline.py +133 -133
  38. crawlo/pipelines/mysql_pipeline.py +195 -176
  39. crawlo/pipelines/pipeline_manager.py +56 -56
  40. crawlo/settings/__init__.py +7 -7
  41. crawlo/settings/default_settings.py +93 -89
  42. crawlo/settings/setting_manager.py +99 -99
  43. crawlo/spider/__init__.py +36 -36
  44. crawlo/stats_collector.py +59 -47
  45. crawlo/subscriber.py +106 -27
  46. crawlo/task_manager.py +27 -27
  47. crawlo/templates/item_template.tmpl +21 -21
  48. crawlo/templates/project_template/main.py +32 -32
  49. crawlo/templates/project_template/setting.py +189 -189
  50. crawlo/templates/spider_template.tmpl +30 -30
  51. crawlo/utils/__init__.py +7 -7
  52. crawlo/utils/concurrency_manager.py +125 -0
  53. crawlo/utils/date_tools.py +177 -177
  54. crawlo/utils/func_tools.py +82 -82
  55. crawlo/utils/log.py +39 -39
  56. crawlo/utils/pqueue.py +173 -173
  57. crawlo/utils/project.py +59 -59
  58. crawlo/utils/request.py +122 -85
  59. crawlo/utils/system.py +11 -11
  60. crawlo/utils/tools.py +303 -0
  61. crawlo/utils/url.py +39 -39
  62. {crawlo-1.0.1.dist-info → crawlo-1.0.3.dist-info}/METADATA +48 -36
  63. crawlo-1.0.3.dist-info/RECORD +80 -0
  64. {crawlo-1.0.1.dist-info → crawlo-1.0.3.dist-info}/top_level.txt +1 -0
  65. tests/__init__.py +7 -0
  66. tests/baidu_spider/__init__.py +7 -0
  67. tests/baidu_spider/demo.py +94 -0
  68. tests/baidu_spider/items.py +25 -0
  69. tests/baidu_spider/middleware.py +49 -0
  70. tests/baidu_spider/pipeline.py +55 -0
  71. tests/baidu_spider/request_fingerprints.txt +9 -0
  72. tests/baidu_spider/run.py +27 -0
  73. tests/baidu_spider/settings.py +78 -0
  74. tests/baidu_spider/spiders/__init__.py +7 -0
  75. tests/baidu_spider/spiders/bai_du.py +61 -0
  76. tests/baidu_spider/spiders/sina.py +79 -0
  77. crawlo-1.0.1.dist-info/RECORD +0 -67
  78. crawlo-1.0.1.dist-info/licenses/LICENSE +0 -23
  79. {crawlo-1.0.1.dist-info → crawlo-1.0.3.dist-info}/WHEEL +0 -0
  80. {crawlo-1.0.1.dist-info → crawlo-1.0.3.dist-info}/entry_points.txt +0 -0
crawlo/network/request.py CHANGED
@@ -1,155 +1,205 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- import hashlib
4
- from copy import deepcopy
5
- from w3lib.url import safe_url_string
6
- from typing import Dict, Optional, Callable, Union, Any
7
-
8
- from crawlo.utils.url import escape_ajax
9
-
10
-
11
- class Request(object):
12
-
13
- def __init__(
14
- self,
15
- url: str,
16
- *,
17
- callback: Optional[Callable] = None,
18
- headers: Optional[Dict[str, str]] = None,
19
- body: Optional[Union[Dict, bytes, str]] = None,
20
- method: Optional[str] = 'GET',
21
- cookies: Optional[Dict[str, str]] = None,
22
- priority: int = 0,
23
- encoding: Optional[str] = 'utf-8',
24
- meta: Optional[Dict[str, Any]] = None,
25
- dont_filter: bool = False,
26
- timeout: Optional[float] = None,
27
- proxy: Optional[str] = None,
28
- allow_redirects: bool = True,
29
- auth: Optional[tuple] = None,
30
- verify: bool = True
31
- ):
32
- # 先初始化基本属性
33
- self.callback = callback
34
- self.headers = headers if headers else {}
35
- self.body = body
36
- self.method = str(method).upper()
37
- self.cookies = cookies if cookies else {}
38
- self.priority = -priority
39
- self.encoding = encoding
40
- self.dont_filter = dont_filter
41
- self._meta = meta if meta is not None else {}
42
- self.timeout = timeout
43
- self.proxy = proxy
44
- self.allow_redirects = allow_redirects
45
- self.auth = auth
46
- self.verify = verify
47
-
48
- # 最后处理URL,确保encoding等依赖属性已初始化
49
- self._set_url(url)
50
-
51
- def copy(self):
52
- return deepcopy(self)
53
-
54
- def set_meta(self, key: str, value: Any) -> None:
55
- self._meta[key] = value
56
-
57
- def _set_url(self, url: str) -> None:
58
- if not isinstance(url, str):
59
- raise TypeError(f"Request url must be str, got {type(url).__name__}")
60
-
61
- s = safe_url_string(url, self.encoding)
62
- self._url = escape_ajax(s)
63
-
64
- if (
65
- "://" not in self._url
66
- and not self._url.startswith("about:")
67
- and not self._url.startswith("data:")
68
- ):
69
- raise ValueError(f"Missing scheme in request url: {self._url}")
70
-
71
- @property
72
- def url(self) -> str:
73
- return self._url
74
-
75
- @property
76
- def meta(self) -> Dict[str, Any]:
77
- return self._meta
78
-
79
- def __str__(self) -> str:
80
- return f'<Request url={self.url} method={self.method}>'
81
-
82
- def __repr__(self) -> str:
83
- return self.__str__()
84
-
85
- def __lt__(self, other) -> bool:
86
- return self.priority < other.priority
87
-
88
-
89
- # #!/usr/bin/python
90
- # # -*- coding:UTF-8 -*-
91
- # import hashlib
92
- # from copy import deepcopy
93
- # from w3lib.url import safe_url_string
94
- # from typing import Dict, Optional, Callable, Union
95
- #
96
- # from crawlo.utils.url import escape_ajax
97
- #
98
- #
99
- # class Request(object):
100
- #
101
- # def __init__(
102
- # self,
103
- # url: str,
104
- # *,
105
- # callback: Optional[Callable] = None,
106
- # headers: Optional[Dict[str, str]] = None,
107
- # body: Optional[Dict] = None,
108
- # method: Optional[str] = 'GET',
109
- # cookies: Optional[Dict[str, str]] = None,
110
- # priority: int = 0,
111
- # encoding: Optional[str] = 'UTF-8',
112
- # meta: Optional[Dict[str, str]] = None,
113
- # dont_filter: bool = False
114
- #
115
- # ):
116
- # self.url = url
117
- # self.callback = callback
118
- # self.headers = headers if headers else {}
119
- # self.body = body
120
- # self.method = str(method).upper()
121
- # self.cookies = cookies
122
- # self.priority = -priority
123
- # self.encoding = encoding
124
- # self.dont_filter = dont_filter
125
- # self._meta = meta if meta is not None else {}
126
- #
127
- # def copy(self):
128
- # return deepcopy(self)
129
- #
130
- # def set_meta(self, key: str, value: str):
131
- # self._meta[key] = value
132
- #
133
- # def _set_url(self, url: str) -> None:
134
- # if not isinstance(url, str):
135
- # raise TypeError(f"Request url must be str, got {type(url).__name__}")
136
- #
137
- # s = safe_url_string(url, self.encoding)
138
- # self._url = escape_ajax(s)
139
- #
140
- # if (
141
- # "://" not in self._url
142
- # and not self._url.startswith("about:")
143
- # and not self._url.startswith("data:")
144
- # ):
145
- # raise ValueError(f"Missing scheme in request url: {self._url}")
146
- #
147
- # @property
148
- # def meta(self):
149
- # return self._meta
150
- #
151
- # def __str__(self):
152
- # return f'<Request url={self.url}> method={self.method}>'
153
- #
154
- # def __lt__(self, other):
155
- # return self.priority < other.priority
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
+ """用于按优先级排序"""
205
+ return self.priority < other.priority
@@ -1,93 +1,166 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- import re
4
- import ujson
5
- from typing import Dict
6
- from parsel import Selector
7
- from http.cookies import SimpleCookie
8
- from urllib.parse import urljoin as _urljoin
9
-
10
- from crawlo import Request
11
- from crawlo.exceptions import DecodeError
12
-
13
-
14
- class Response(object):
15
-
16
- def __init__(
17
- self,
18
- url: str,
19
- *,
20
- headers: Dict,
21
- body: bytes = b"",
22
- method: str = 'GET',
23
- request: Request = None,
24
- status_code: int = 200,
25
- ):
26
- self.url = url
27
- self.headers = headers
28
- self.body = body
29
- self.method = method
30
- self.request = request
31
- self.status_code = status_code
32
- self.encoding = request.encoding
33
- self._selector = None
34
- self._text_cache = None
35
-
36
- @property
37
- def text(self):
38
- # 请求缓存
39
- if self._text_cache:
40
- return self._text_cache
41
- try:
42
- self._text_cache = self.body.decode(self.encoding)
43
- except UnicodeDecodeError:
44
- try:
45
- _encoding_re = re.compile(r"charset=([\w-]+)", flags=re.I)
46
- _encoding_string = self.headers.get('Content-Type', '') or self.headers.get('content-type', '')
47
- _encoding = _encoding_re.search(_encoding_string)
48
- if _encoding:
49
- _encoding = _encoding.group(1)
50
- self._text_cache = self.body.decode(_encoding)
51
- else:
52
- raise DecodeError(f"{self.request} {self.request.encoding} error.")
53
- except UnicodeDecodeError as exp:
54
- raise UnicodeDecodeError(
55
- exp.encoding, exp.object, exp.start, exp.end, f"{self.request} error."
56
- )
57
- return self._text_cache
58
-
59
- def json(self):
60
- return ujson.loads(self.text)
61
-
62
- def urljoin(self, url):
63
- return _urljoin(self.url, url)
64
-
65
- def xpath(self, xpath_str):
66
- if self._selector is None:
67
- self._selector = Selector(self.text)
68
- return self._selector.xpath(xpath_str)
69
-
70
- def css(self, css_str):
71
- if self._selector is None:
72
- self._selector = Selector(self.text)
73
- return self._selector.css(css_str)
74
-
75
- def re_search(self, pattern, flags=re.DOTALL):
76
- return re.search(pattern, self.text, flags=flags)
77
-
78
- def re_findall(self, pattern, flags=re.DOTALL):
79
- return re.findall(pattern, self.text, flags=flags)
80
-
81
- def get_cookies(self):
82
- cookie_headers = self.headers.getlist('Set-Cookie') or []
83
- cookies = SimpleCookie()
84
- for header in cookie_headers:
85
- cookies.load(header)
86
- return {k: v.value for k, v in cookies.items()}
87
-
88
- @property
89
- def meta(self):
90
- return self.request.meta
91
-
92
- def __str__(self):
93
- return f"{self.url} {self.status_code} {self.request.encoding} "
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ import re
4
+ import ujson
5
+ from typing import Dict, Any, List, Optional
6
+ from parsel import Selector, SelectorList
7
+ from http.cookies import SimpleCookie
8
+ from urllib.parse import urljoin as _urljoin
9
+
10
+ from crawlo import Request
11
+ from crawlo.exceptions import DecodeError
12
+
13
+
14
+ class Response:
15
+ """
16
+ HTTP响应的封装,提供数据解析的便捷方法。
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ url: str,
22
+ *,
23
+ headers: Dict[str, Any],
24
+ body: bytes = b"",
25
+ method: str = 'GET',
26
+ request: Request = None,
27
+ status_code: int = 200,
28
+ ):
29
+ self.url = url
30
+ self.headers = headers
31
+ self.body = body
32
+ self.method = method
33
+ self.request = request
34
+ self.status_code = status_code
35
+ self.encoding = self.request.encoding if self.request else None
36
+ self._text_cache = None
37
+ self._json_cache = None
38
+ self._selector_instance = None # 修改变量名,避免与 @property 冲突
39
+
40
+ @property
41
+ def text(self) -> str:
42
+ """将响应体(body)以正确的编码解码为字符串,并缓存结果。"""
43
+ if self._text_cache is not None:
44
+ return self._text_cache
45
+
46
+ encoding = self.encoding
47
+ try:
48
+ # 优先使用 request 提供的编码
49
+ if encoding:
50
+ self._text_cache = self.body.decode(encoding)
51
+ return self._text_cache
52
+
53
+ # Content-Type 中提取编码
54
+ content_type = self.headers.get("Content-Type", "")
55
+ charset_match = re.search(r"charset=([\w-]+)", content_type, re.I)
56
+ if charset_match:
57
+ encoding = charset_match.group(1)
58
+ self._text_cache = self.body.decode(encoding)
59
+ return self._text_cache
60
+
61
+ # 默认尝试 UTF-8
62
+ self._text_cache = self.body.decode("utf-8")
63
+ return self._text_cache
64
+
65
+ except UnicodeDecodeError as e:
66
+ raise DecodeError(f"Failed to decode response from {self.url}: {e}")
67
+
68
+ def json(self) -> Any:
69
+ """将响应文本解析为 JSON 对象。"""
70
+ if self._json_cache:
71
+ return self._json_cache
72
+ self._json_cache = ujson.loads(self.text)
73
+ return self._json_cache
74
+
75
+ def urljoin(self, url: str) -> str:
76
+ """拼接 URL,自动处理相对路径。"""
77
+ return _urljoin(self.url, url)
78
+
79
+ @property
80
+ def _selector(self) -> Selector:
81
+ """懒加载 Selector 实例"""
82
+ if self._selector_instance is None:
83
+ self._selector_instance = Selector(self.text)
84
+ return self._selector_instance
85
+
86
+ def xpath(self, query: str) -> SelectorList:
87
+ """使用 XPath 选择器查询文档。"""
88
+ return self._selector.xpath(query)
89
+
90
+ def css(self, query: str) -> SelectorList:
91
+ """使用 CSS 选择器查询文档。"""
92
+ return self._selector.css(query)
93
+
94
+ def xpath_text(self, query: str) -> str:
95
+ """使用 XPath 提取并返回纯文本。"""
96
+ fragments = self.xpath(f"{query}//text()").getall()
97
+ return " ".join(text.strip() for text in fragments if text.strip())
98
+
99
+ def css_text(self, query: str) -> str:
100
+ """使用 CSS 选择器提取并返回纯文本。"""
101
+ fragments = self.css(f"{query} ::text").getall()
102
+ return " ".join(text.strip() for text in fragments if text.strip())
103
+
104
+ def get_text(self, xpath_or_css: str, join_str: str = " ") -> str:
105
+ """
106
+ 获取指定节点的纯文本(自动拼接子节点文本)
107
+
108
+ 参数:
109
+ xpath_or_css: XPath或CSS选择器
110
+ join_str: 文本拼接分隔符(默认为空格)
111
+
112
+ 返回:
113
+ 拼接后的纯文本字符串
114
+ """
115
+ elements = self.xpath(xpath_or_css) if xpath_or_css.startswith(('/', '//', './')) else self.css(xpath_or_css)
116
+ texts = elements.xpath('.//text()').getall()
117
+ return join_str.join(text.strip() for text in texts if text.strip())
118
+
119
+ def get_all_text(self, xpath_or_css: str, join_str: str = " ") -> List[str]:
120
+ """
121
+ 获取多个节点的纯文本列表
122
+
123
+ 参数:
124
+ xpath_or_css: XPath或CSS选择器
125
+ join_str: 单个节点内文本拼接分隔符
126
+
127
+ 返回:
128
+ 纯文本列表(每个元素对应一个节点的文本)
129
+ """
130
+ elements = self.xpath(xpath_or_css) if xpath_or_css.startswith(('/', '//', './')) else self.css(xpath_or_css)
131
+ result = []
132
+ for element in elements:
133
+ texts = element.xpath('.//text()').getall()
134
+ clean_text = join_str.join(text.strip() for text in texts if text.strip())
135
+ if clean_text:
136
+ result.append(clean_text)
137
+ return result
138
+
139
+ def re_search(self, pattern: str, flags: int = re.DOTALL) -> Optional[re.Match]:
140
+ """在响应文本上执行正则表达式搜索。"""
141
+ if not isinstance(pattern, str):
142
+ raise TypeError("Pattern must be a string")
143
+ return re.search(pattern, self.text, flags=flags)
144
+
145
+ def re_findall(self, pattern: str, flags: int = re.DOTALL) -> List[Any]:
146
+ """在响应文本上执行正则表达式查找。"""
147
+ if not isinstance(pattern, str):
148
+ raise TypeError("Pattern must be a string")
149
+ return re.findall(pattern, self.text, flags=flags)
150
+
151
+ def get_cookies(self) -> Dict[str, str]:
152
+ """从响应头中解析并返回Cookies。"""
153
+ cookie_header = self.headers.get("Set-Cookie", "")
154
+ if isinstance(cookie_header, list):
155
+ cookie_header = ", ".join(cookie_header)
156
+ cookies = SimpleCookie()
157
+ cookies.load(cookie_header)
158
+ return {key: morsel.value for key, morsel in cookies.items()}
159
+
160
+ @property
161
+ def meta(self) -> Dict:
162
+ """获取关联的 Request 对象的 meta 字典。"""
163
+ return self.request.meta if self.request else {}
164
+
165
+ def __str__(self):
166
+ return f"<{self.status_code} {self.url}>"
@@ -1,13 +1,13 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- from crawlo.items.items import Item
4
-
5
-
6
- class BasePipeline:
7
-
8
- def process_item(self, item: Item, spider):
9
- raise NotImplementedError
10
-
11
- @classmethod
12
- def create_instance(cls, crawler):
13
- return cls()
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ from crawlo.items.items import Item
4
+
5
+
6
+ class BasePipeline:
7
+
8
+ def process_item(self, item: Item, spider):
9
+ raise NotImplementedError
10
+
11
+ @classmethod
12
+ def create_instance(cls, crawler):
13
+ return cls()