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/utils/request.py CHANGED
@@ -1,85 +1,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 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='utf-8') -> bytes:
17
- """
18
- 将各种类型统一转换为 bytes。
19
- 支持 str, bytes, dict, None 及其他可转为字符串的类型。
20
- """
21
- if isinstance(data, bytes):
22
- return data
23
- if isinstance(data, str):
24
- return data.encode(encoding)
25
- if isinstance(data, dict):
26
- return json.dumps(data, sort_keys=True, ensure_ascii=False).encode(encoding)
27
- if data is None:
28
- return b''
29
- return str(data).encode(encoding)
30
-
31
-
32
- def request_fingerprint(
33
- request: Request,
34
- include_headers: Optional[Iterable[Union[bytes, str]]] = None
35
- ) -> str:
36
- """
37
- 生成请求指纹,基于方法、标准化 URL、body 和可选的 headers。
38
- 使用 SHA256 哈希算法以提高安全性。
39
-
40
- :param request: Request 对象(需包含 method, url, body, headers)
41
- :param include_headers: 指定要参与指纹计算的 header 名称列表(str 或 bytes)
42
- :return: 请求指纹(hex string)
43
- """
44
- hash_func = hashlib.sha256()
45
-
46
- # 基本字段
47
- hash_func.update(to_bytes(request.method))
48
- hash_func.update(to_bytes(canonicalize_url(request.url)))
49
- hash_func.update(request.body or b'')
50
-
51
- # 处理 headers
52
- if include_headers:
53
- headers = request.headers # 假设 headers 是类似字典或 MultiDict 的结构
54
- for header_name in include_headers:
55
- name_bytes = to_bytes(header_name).lower() # 统一转为小写进行匹配
56
- value = b''
57
-
58
- # 兼容 headers 的访问方式(如 MultiDict 或 dict)
59
- if hasattr(headers, 'get_all'):
60
- # 如 scrapy.http.Headers 的 get_all 方法
61
- values = headers.get_all(name_bytes)
62
- value = b';'.join(values) if values else b''
63
- elif hasattr(headers, '__getitem__'):
64
- # 如普通 dict
65
- try:
66
- raw_value = headers[name_bytes]
67
- if isinstance(raw_value, list):
68
- value = b';'.join(to_bytes(v) for v in raw_value)
69
- else:
70
- value = to_bytes(raw_value)
71
- except (KeyError, TypeError):
72
- value = b''
73
- else:
74
- value = b''
75
-
76
- hash_func.update(name_bytes + b':' + value)
77
-
78
- return hash_func.hexdigest()
79
-
80
-
81
- def set_request(request: Request, priority: int) -> None:
82
- request.meta['depth'] = request.meta.setdefault('depth', 0) + 1
83
- if priority:
84
- request.priority -= request.meta['depth'] * priority
85
-
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
+
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
+
crawlo/utils/tools.py ADDED
@@ -0,0 +1,303 @@
1
+ import json
2
+ import re
3
+ from pprint import pformat
4
+ from datetime import date, time, datetime
5
+
6
+ from crawlo.utils.log import get_logger
7
+
8
+
9
+ logger = get_logger(__name__)
10
+
11
+
12
+ def make_insert_sql(
13
+ table, data, auto_update=False, update_columns=(), insert_ignore=False
14
+ ):
15
+ """
16
+ @summary: 适用于mysql
17
+ ---------
18
+ @param table:
19
+ @param data: 表数据 json格式
20
+ @param auto_update: 使用的是replace into, 为完全覆盖已存在的数据
21
+ @param update_columns: 需要更新的列 默认全部,当指定值时,auto_update设置无效,当duplicate key冲突时更新指定的列
22
+ @param insert_ignore: 数据存在忽略
23
+ ---------
24
+ @result:
25
+ """
26
+
27
+ keys = ["`{}`".format(key) for key in data.keys()]
28
+ keys = list2str(keys).replace("'", "")
29
+
30
+ values = [format_sql_value(value) for value in data.values()]
31
+ values = list2str(values)
32
+
33
+ if update_columns:
34
+ if not isinstance(update_columns, (tuple, list)):
35
+ update_columns = [update_columns]
36
+ update_columns_ = ", ".join(
37
+ ["{key}=values({key})".format(key=key) for key in update_columns]
38
+ )
39
+ sql = (
40
+ "insert%s into `{table}` {keys} values {values} on duplicate key update %s"
41
+ % (" ignore" if insert_ignore else "", update_columns_)
42
+ )
43
+
44
+ elif auto_update:
45
+ sql = "replace into `{table}` {keys} values {values}"
46
+ else:
47
+ sql = "insert%s into `{table}` {keys} values {values}" % (
48
+ " ignore" if insert_ignore else ""
49
+ )
50
+
51
+ sql = sql.format(table=table, keys=keys, values=values).replace("None", "null")
52
+ return sql
53
+
54
+
55
+ def make_update_sql(table, data, condition):
56
+ """
57
+ @summary: 适用于mysql, oracle数据库时间需要to_date 处理(TODO)
58
+ ---------
59
+ @param table:
60
+ @param data: 表数据 json格式
61
+ @param condition: where 条件
62
+ ---------
63
+ @result:
64
+ """
65
+ key_values = []
66
+
67
+ for key, value in data.items():
68
+ value = format_sql_value(value)
69
+ if isinstance(value, str):
70
+ key_values.append("`{}`={}".format(key, repr(value)))
71
+ elif value is None:
72
+ key_values.append("`{}`={}".format(key, "null"))
73
+ else:
74
+ key_values.append("`{}`={}".format(key, value))
75
+
76
+ key_values = ", ".join(key_values)
77
+
78
+ sql = "update `{table}` set {key_values} where {condition}"
79
+ sql = sql.format(table=table, key_values=key_values, condition=condition)
80
+ return sql
81
+
82
+
83
+ def make_batch_sql(
84
+ table, datas, auto_update=False, update_columns=(), update_columns_value=()
85
+ ):
86
+ """
87
+ @summary: 生成批量的SQL
88
+ ---------
89
+ @param table:
90
+ @param datas: 表数据 [{...}]
91
+ @param auto_update: 使用的是replace into,为完全覆盖已存在的数据
92
+ @param update_columns: 需要更新的列,默认全部,当指定值时,auto_update设置无效,当duplicate key冲突时更新指定的列
93
+ @param update_columns_value: 需要更新的列的值,默认为datas里边对应的值,注意如果值为字符串类型需要主动加单引号,如 update_columns_value=("'test'",)
94
+ ---------
95
+ @result:
96
+ """
97
+ if not datas:
98
+ return
99
+
100
+ keys = list(set([key for data in datas for key in data]))
101
+ # values_placeholder = ["%s"] * len(keys)
102
+ values = []
103
+ for data in datas:
104
+ # 检查 data 是否是字典类型
105
+ if not isinstance(data, dict):
106
+ # 如果 data 不是字典,记录错误日志并打印 data 的内容和类型
107
+ # logger.error(f"期望的数据类型是字典,但实际得到: {data} (类型: {type(data)})")
108
+ continue # 跳过非字典类型的 data,继续处理下一个数据
109
+
110
+ value = []
111
+ for key in keys:
112
+ # 从字典中获取当前 key 对应的值
113
+ current_data = data.get(key)
114
+ try:
115
+ # 对值进行格式化处理
116
+ current_data = format_sql_value(current_data)
117
+ value.append(current_data) # 将处理后的值添加到列表中
118
+ except Exception as e:
119
+ # 如果格式化失败,记录错误日志
120
+ logger.error(f"{key}: {current_data} (类型: {type(current_data)}) -> {e}")
121
+
122
+ # 将处理后的值列表添加到 values 中
123
+ values.append(value)
124
+ keys_str = ", ".join(["`{}`".format(key) for key in keys])
125
+ placeholders_str = ", ".join(["%s"] * len(keys))
126
+
127
+ if update_columns:
128
+ if not isinstance(update_columns, (tuple, list)):
129
+ update_columns = [update_columns]
130
+ if update_columns_value:
131
+ update_columns_ = ", ".join(
132
+ [
133
+ "`{key}`={value}".format(key=key, value=value)
134
+ for key, value in zip(update_columns, update_columns_value)
135
+ ]
136
+ )
137
+ else:
138
+ # 修改这里,使用 VALUES() 函数来引用插入的值
139
+ update_columns_ = ", ".join(
140
+ ["`{key}`=VALUES(`{key}`)".format(key=key) for key in update_columns]
141
+ )
142
+
143
+ sql = f"INSERT INTO `{table}` ({keys_str}) VALUES ({placeholders_str}) ON DUPLICATE KEY UPDATE {update_columns_}"
144
+ elif auto_update:
145
+ sql = "REPLACE INTO `{table}` ({keys}) VALUES ({values_placeholder})".format(
146
+ table=table, keys=keys_str, values_placeholder=placeholders_str
147
+ )
148
+ else:
149
+ sql = "INSERT IGNORE INTO `{table}` ({keys}) VALUES ({values_placeholder})".format(
150
+ table=table, keys=keys_str, values_placeholder=placeholders_str
151
+ )
152
+ return sql, values
153
+
154
+
155
+ def format_sql_value(value):
156
+ """
157
+ 格式化 SQL 值
158
+ """
159
+ if value is None:
160
+ return None # 处理 NULL 值
161
+
162
+ # 确保处理字符串
163
+ if isinstance(value, str):
164
+ return value.strip() # 去除首尾空格
165
+
166
+ # 处理列表或元组类型
167
+ elif isinstance(value, (list, tuple)):
168
+ try:
169
+ return dumps_json(value) # 将其转为 JSON 字符串
170
+ except Exception as e:
171
+ raise ValueError(f"Failed to serialize list/tuple to JSON: {value}, error: {e}")
172
+
173
+ # 处理字典类型
174
+ elif isinstance(value, dict):
175
+ try:
176
+ return dumps_json(value) # 将其转为 JSON 字符串
177
+ except Exception as e:
178
+ raise ValueError(f"Failed to serialize dict to JSON: {value}, error: {e}")
179
+
180
+ # 处理布尔类型
181
+ elif isinstance(value, bool):
182
+ return int(value) # 转为整数
183
+
184
+ # 确保数值类型优先匹配
185
+ elif isinstance(value, (int, float)):
186
+ return value # 返回数值
187
+
188
+ # 处理日期、时间类型
189
+ elif isinstance(value, (date, time, datetime)):
190
+ return str(value) # 转换为字符串表示
191
+
192
+ # 如果遇到无法处理的类型,抛出异常
193
+ else:
194
+ raise TypeError(f"Unsupported value type: {type(value)}, value: {value}")
195
+
196
+
197
+
198
+
199
+ def list2str(datas):
200
+ """
201
+ 列表转字符串
202
+ :param datas: [1, 2]
203
+ :return: (1, 2)
204
+ """
205
+ data_str = str(tuple(datas))
206
+ data_str = re.sub(r",\)$", ")", data_str)
207
+ return data_str
208
+
209
+ _REGEXPS = {}
210
+
211
+ def get_info(html, regexps, allow_repeat=True, fetch_one=False, split=None):
212
+ regexps = isinstance(regexps, str) and [regexps] or regexps
213
+
214
+ infos = []
215
+ for regex in regexps:
216
+ if regex == "":
217
+ continue
218
+
219
+ if regex not in _REGEXPS.keys():
220
+ _REGEXPS[regex] = re.compile(regex, re.S)
221
+
222
+ if fetch_one:
223
+ infos = _REGEXPS[regex].search(html)
224
+ if infos:
225
+ infos = infos.groups()
226
+ else:
227
+ continue
228
+ else:
229
+ infos = _REGEXPS[regex].findall(str(html))
230
+
231
+ if len(infos) > 0:
232
+ break
233
+
234
+ if fetch_one:
235
+ infos = infos if infos else ("",)
236
+ return infos if len(infos) > 1 else infos[0]
237
+ else:
238
+ infos = allow_repeat and infos or sorted(set(infos), key=infos.index)
239
+ infos = split.join(infos) if split else infos
240
+ return infos
241
+
242
+
243
+ def get_json(json_str):
244
+ """
245
+ @summary: 取json对象
246
+ ---------
247
+ @param json_str: json格式的字符串
248
+ ---------
249
+ @result: 返回json对象
250
+ """
251
+
252
+ try:
253
+ return json.loads(json_str) if json_str else {}
254
+ except Exception as e1:
255
+ try:
256
+ json_str = json_str.strip()
257
+ json_str = json_str.replace("'", '"')
258
+ keys = get_info(json_str, r"(\w+):")
259
+ for key in keys:
260
+ json_str = json_str.replace(key, '"%s"' % key)
261
+
262
+ return json.loads(json_str) if json_str else {}
263
+
264
+ except Exception as e2:
265
+ logger.error(
266
+ """
267
+ e1: %s
268
+ format json_str: %s
269
+ e2: %s
270
+ """
271
+ % (e1, json_str, e2)
272
+ )
273
+
274
+ return {}
275
+
276
+
277
+ def dumps_json(data, indent=4, sort_keys=False):
278
+ """
279
+ @summary: 格式化json 用于打印
280
+ ---------
281
+ @param data: json格式的字符串或json对象
282
+ @param indent:
283
+ @param sort_keys:
284
+ ---------
285
+ @result: 格式化后的字符串
286
+ """
287
+ try:
288
+ if isinstance(data, str):
289
+ data = get_json(data)
290
+
291
+ data = json.dumps(
292
+ data,
293
+ ensure_ascii=False,
294
+ indent=indent,
295
+ skipkeys=True,
296
+ sort_keys=sort_keys,
297
+ default=str,
298
+ )
299
+
300
+ except Exception as e:
301
+ data = pformat(data)
302
+
303
+ return data
crawlo/utils/url.py CHANGED
@@ -1,40 +1,40 @@
1
- from urllib.parse import urldefrag
2
- from w3lib.url import add_or_replace_parameter
3
-
4
-
5
- def escape_ajax(url: str) -> str:
6
- """
7
- 根据Google AJAX爬取规范转换URL(处理哈希片段#!):
8
- https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
9
-
10
- 规则说明:
11
- 1. 仅当URL包含 `#!` 时才转换(表示这是AJAX可爬取页面)
12
- 2. 将 `#!key=value` 转换为 `?_escaped_fragment_=key%3Dvalue`
13
- 3. 保留原始查询参数(如果有)
14
-
15
- 示例:
16
- >>> escape_ajax("www.example.com/ajax.html#!key=value")
17
- 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
18
- >>> escape_ajax("www.example.com/ajax.html?k1=v1#!key=value")
19
- 'www.example.com/ajax.html?k1=v1&_escaped_fragment_=key%3Dvalue'
20
- >>> escape_ajax("www.example.com/ajax.html#!")
21
- 'www.example.com/ajax.html?_escaped_fragment_='
22
-
23
- 非AJAX可爬取的URL(无#!)原样返回:
24
- >>> escape_ajax("www.example.com/ajax.html#normal")
25
- 'www.example.com/ajax.html#normal'
26
- """
27
- # 分离URL的基础部分和哈希片段
28
- de_frag, frag = urldefrag(url)
29
-
30
- # 仅处理以"!"开头的哈希片段(Google规范)
31
- if not frag.startswith("!"):
32
- return url # 不符合规则则原样返回
33
-
34
- # 调用辅助函数添加 `_escaped_fragment_` 参数
35
- return add_or_replace_parameter(de_frag, "_escaped_fragment_", frag[1:])
36
-
37
-
38
- if __name__ == '__main__':
39
- f = escape_ajax('http://example.com/page#!')
1
+ from urllib.parse import urldefrag
2
+ from w3lib.url import add_or_replace_parameter
3
+
4
+
5
+ def escape_ajax(url: str) -> str:
6
+ """
7
+ 根据Google AJAX爬取规范转换URL(处理哈希片段#!):
8
+ https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
9
+
10
+ 规则说明:
11
+ 1. 仅当URL包含 `#!` 时才转换(表示这是AJAX可爬取页面)
12
+ 2. 将 `#!key=value` 转换为 `?_escaped_fragment_=key%3Dvalue`
13
+ 3. 保留原始查询参数(如果有)
14
+
15
+ 示例:
16
+ >>> escape_ajax("www.example.com/ajax.html#!key=value")
17
+ 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
18
+ >>> escape_ajax("www.example.com/ajax.html?k1=v1#!key=value")
19
+ 'www.example.com/ajax.html?k1=v1&_escaped_fragment_=key%3Dvalue'
20
+ >>> escape_ajax("www.example.com/ajax.html#!")
21
+ 'www.example.com/ajax.html?_escaped_fragment_='
22
+
23
+ 非AJAX可爬取的URL(无#!)原样返回:
24
+ >>> escape_ajax("www.example.com/ajax.html#normal")
25
+ 'www.example.com/ajax.html#normal'
26
+ """
27
+ # 分离URL的基础部分和哈希片段
28
+ de_frag, frag = urldefrag(url)
29
+
30
+ # 仅处理以"!"开头的哈希片段(Google规范)
31
+ if not frag.startswith("!"):
32
+ return url # 不符合规则则原样返回
33
+
34
+ # 调用辅助函数添加 `_escaped_fragment_` 参数
35
+ return add_or_replace_parameter(de_frag, "_escaped_fragment_", frag[1:])
36
+
37
+
38
+ if __name__ == '__main__':
39
+ f = escape_ajax('http://example.com/page#!')
40
40
  print(f)