selectolax 0.3.28__cp38-cp38-musllinux_1_2_aarch64.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 selectolax might be problematic. Click here for more details.

selectolax/parser.pyx ADDED
@@ -0,0 +1,433 @@
1
+
2
+ from cpython cimport bool
3
+
4
+ include "modest/selection.pxi"
5
+ include "modest/node.pxi"
6
+ include "modest/util.pxi"
7
+ include "utils.pxi"
8
+
9
+ cdef class HTMLParser:
10
+ """The HTML parser.
11
+
12
+ Use this class to parse raw HTML.
13
+
14
+ Parameters
15
+ ----------
16
+
17
+ html : str (unicode) or bytes
18
+ detect_encoding : bool, default True
19
+ If `True` and html type is `bytes` then encoding will be detected automatically.
20
+ use_meta_tags : bool, default True
21
+ Whether to use meta tags in encoding detection process.
22
+ decode_errors : str, default 'ignore'
23
+ Same as in builtin's str.decode, i.e 'strict', 'ignore' or 'replace'.
24
+ """
25
+ def __init__(self, html, detect_encoding=True, use_meta_tags=True, decode_errors = 'ignore'):
26
+
27
+ cdef size_t html_len
28
+ cdef char* html_chars
29
+
30
+ self.detect_encoding = detect_encoding
31
+ self.use_meta_tags = use_meta_tags
32
+ self.decode_errors = decode_errors
33
+ self._encoding = MyENCODING_UTF_8
34
+
35
+ bytes_html, html_len = preprocess_input(html, decode_errors)
36
+ html_chars = <char*> bytes_html
37
+
38
+ if detect_encoding and isinstance(html, bytes):
39
+ self._detect_encoding(html_chars, html_len)
40
+
41
+ self._parse_html(html_chars, html_len)
42
+
43
+ self.raw_html = bytes_html
44
+ self.cached_script_texts = None
45
+ self.cached_script_srcs = None
46
+
47
+ def css(self, str query):
48
+ """A CSS selector.
49
+
50
+ Matches pattern `query` against HTML tree.
51
+ `CSS selectors reference <https://www.w3schools.com/cssref/css_selectors.asp>`_.
52
+
53
+ Parameters
54
+ ----------
55
+ query : str
56
+ CSS selector (e.g. "div > :nth-child(2n+1):not(:has(a))").
57
+
58
+ Returns
59
+ -------
60
+ selector : list of `Node` objects
61
+
62
+ """
63
+
64
+ node = Node()
65
+ node._init(self.html_tree.node_html, self)
66
+ return node.css(query)
67
+
68
+ def css_first(self, str query, default=None, strict=False):
69
+ """Same as `css` but returns only the first match.
70
+
71
+ Parameters
72
+ ----------
73
+
74
+ query : str
75
+ default : bool, default None
76
+ Default value to return if there is no match.
77
+ strict: bool, default True
78
+ Set to True if you want to check if there is strictly only one match in the document.
79
+
80
+
81
+ Returns
82
+ -------
83
+ selector : `Node` object
84
+
85
+ """
86
+
87
+ node = Node()
88
+ node._init(self.html_tree.node_html, self)
89
+ return node.css_first(query, default, strict)
90
+
91
+ cdef void _detect_encoding(self, char* html, size_t html_len) nogil:
92
+ cdef myencoding_t encoding = MyENCODING_DEFAULT;
93
+
94
+ if self.use_meta_tags:
95
+ encoding = myencoding_prescan_stream_to_determine_encoding(html, html_len)
96
+ if encoding != MyENCODING_DEFAULT and encoding != MyENCODING_NOT_DETERMINED:
97
+ self._encoding = encoding
98
+ return
99
+
100
+ if not myencoding_detect_bom(html, html_len, &encoding):
101
+ myencoding_detect(html, html_len, &encoding)
102
+
103
+ self._encoding = encoding
104
+
105
+ cdef _parse_html(self, char* html, size_t html_len):
106
+ cdef myhtml_t* myhtml
107
+ cdef mystatus_t status
108
+
109
+ with nogil:
110
+ myhtml = myhtml_create()
111
+ status = myhtml_init(myhtml, MyHTML_OPTIONS_DEFAULT, 1, 0)
112
+
113
+ if status != 0:
114
+ raise RuntimeError("Can't init MyHTML object.")
115
+
116
+ with nogil:
117
+ self.html_tree = myhtml_tree_create()
118
+ status = myhtml_tree_init(self.html_tree, myhtml)
119
+
120
+ if status != 0:
121
+ raise RuntimeError("Can't init MyHTML Tree object.")
122
+
123
+ with nogil:
124
+ status = myhtml_parse(self.html_tree, self._encoding, html, html_len)
125
+
126
+ if status != 0:
127
+ raise RuntimeError("Can't parse HTML:\n%s" % str(html))
128
+
129
+ assert self.html_tree.node_html != NULL
130
+
131
+
132
+ @property
133
+ def input_encoding(self):
134
+ """Return encoding of the HTML document.
135
+
136
+ Returns `unknown` in case the encoding is not determined.
137
+ """
138
+ cdef const char* encoding
139
+ encoding = myencoding_name_by_id(self._encoding, NULL)
140
+
141
+ if encoding != NULL:
142
+ return encoding.decode('utf-8')
143
+ else:
144
+ return 'unknown'
145
+
146
+ @property
147
+ def root(self):
148
+ """Returns root node."""
149
+ if self.html_tree and self.html_tree.node_html:
150
+ node = Node()
151
+ node._init(self.html_tree.node_html, self)
152
+ return node
153
+ return None
154
+
155
+ @property
156
+ def head(self):
157
+ """Returns head node."""
158
+ cdef myhtml_tree_node_t* head
159
+ head = myhtml_tree_get_node_head(self.html_tree)
160
+
161
+ if head != NULL:
162
+ node = Node()
163
+ node._init(head, self)
164
+ return node
165
+ return None
166
+
167
+ @property
168
+ def body(self):
169
+ """Returns document body."""
170
+ cdef myhtml_tree_node_t* body
171
+ body = myhtml_tree_get_node_body(self.html_tree)
172
+
173
+ if body != NULL:
174
+ node = Node()
175
+ node._init(body, self)
176
+ return node
177
+
178
+ return None
179
+
180
+ def tags(self, str name):
181
+ """Returns a list of tags that match specified name.
182
+
183
+ Parameters
184
+ ----------
185
+ name : str (e.g. div)
186
+
187
+ """
188
+ cdef myhtml_collection_t* collection = NULL
189
+ pybyte_name = name.encode('UTF-8')
190
+ cdef mystatus_t status = 0;
191
+
192
+ result = list()
193
+ collection = myhtml_get_nodes_by_name(self.html_tree, NULL, pybyte_name, len(pybyte_name), &status)
194
+
195
+ if collection == NULL:
196
+ return result
197
+
198
+ if status == 0:
199
+ for i in range(collection.length):
200
+ node = Node()
201
+ node._init(collection.list[i], self)
202
+ result.append(node)
203
+
204
+ myhtml_collection_destroy(collection)
205
+
206
+ return result
207
+
208
+ def text(self, bool deep=True, str separator='', bool strip=False):
209
+ """Returns the text of the node including text of all its child nodes.
210
+
211
+ Parameters
212
+ ----------
213
+ strip : bool, default False
214
+ If true, calls ``str.strip()`` on each text part to remove extra white spaces.
215
+ separator : str, default ''
216
+ The separator to use when joining text from different nodes.
217
+ deep : bool, default True
218
+ If True, includes text from all child nodes.
219
+
220
+ Returns
221
+ -------
222
+ text : str
223
+
224
+ """
225
+ if not self.body:
226
+ return ""
227
+ return self.body.text(deep=deep, separator=separator, strip=strip)
228
+
229
+ def strip_tags(self, list tags, bool recursive = False):
230
+ """Remove specified tags from the node.
231
+
232
+ Parameters
233
+ ----------
234
+ tags : list of str
235
+ List of tags to remove.
236
+ recursive : bool, default True
237
+ Whenever to delete all its child nodes
238
+
239
+ Examples
240
+ --------
241
+
242
+ >>> tree = HTMLParser('<html><head></head><body><script></script><div>Hello world!</div></body></html>')
243
+ >>> tags = ['head', 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes']
244
+ >>> tree.strip_tags(tags)
245
+ >>> tree.html
246
+ '<html><body><div>Hello world!</div></body></html>'
247
+
248
+ """
249
+ cdef myhtml_collection_t* collection = NULL
250
+
251
+ cdef mystatus_t status = 0;
252
+
253
+ for tag in tags:
254
+ pybyte_name = tag.encode('UTF-8')
255
+ collection = myhtml_get_nodes_by_name(self.html_tree, NULL, pybyte_name, len(pybyte_name), &status)
256
+
257
+ if collection == NULL:
258
+ continue
259
+
260
+ if status != 0:
261
+ continue
262
+
263
+ for i in range(collection.length):
264
+ if recursive:
265
+ myhtml_node_delete_recursive(collection.list[i])
266
+ else:
267
+ myhtml_node_delete(collection.list[i])
268
+
269
+ myhtml_collection_destroy(collection)
270
+
271
+
272
+ def unwrap_tags(self, list tags):
273
+ """Unwraps specified tags from the HTML tree.
274
+
275
+ Works the same as th `unwrap` method, but applied to a list of tags.
276
+
277
+ Parameters
278
+ ----------
279
+ tags : list
280
+ List of tags to remove.
281
+
282
+ Examples
283
+ --------
284
+
285
+ >>> tree = HTMLParser("<div><a href="">Hello</a> <i>world</i>!</div>")
286
+ >>> tree.head.unwrap_tags(['i','a'])
287
+ >>> tree.head.html
288
+ '<body><div>Hello world!</div></body>'
289
+ """
290
+ if self.root is not None:
291
+ self.root.unwrap_tags(tags)
292
+
293
+ @property
294
+ def html(self):
295
+ """Return HTML representation of the page."""
296
+ if self.html_tree and self.html_tree.document:
297
+ node = Node()
298
+ node._init(self.html_tree.document, self)
299
+ return node.html
300
+ return None
301
+
302
+ def select(self, query=None):
303
+ """Select nodes given a CSS selector.
304
+
305
+ Works similarly to the ``css`` method, but supports chained filtering and extra features.
306
+
307
+ Parameters
308
+ ----------
309
+ query : str or None
310
+ The CSS selector to use when searching for nodes.
311
+
312
+ Returns
313
+ -------
314
+ selector : The `Selector` class.
315
+ """
316
+ cdef Node node
317
+ node = self.root
318
+ if node:
319
+ return Selector(node, query)
320
+
321
+ def any_css_matches(self, tuple selectors):
322
+ """Returns True if any of the specified CSS selectors matches a node."""
323
+ return self.root.any_css_matches(selectors)
324
+
325
+ def scripts_contain(self, str query):
326
+ """Returns True if any of the script tags contain specified text.
327
+
328
+ Caches script tags on the first call to improve performance.
329
+
330
+ Parameters
331
+ ----------
332
+ query : str
333
+ The query to check.
334
+
335
+ """
336
+ return self.root.scripts_contain(query)
337
+
338
+ def script_srcs_contain(self, tuple queries):
339
+ """Returns True if any of the script SRCs attributes contain on of the specified text.
340
+
341
+ Caches values on the first call to improve performance.
342
+
343
+ Parameters
344
+ ----------
345
+ queries : tuple of str
346
+
347
+ """
348
+ return self.root.script_srcs_contain(queries)
349
+
350
+ def css_matches(self, str selector):
351
+ return self.root.css_matches(selector)
352
+ def merge_text_nodes(self):
353
+ """Iterates over all text nodes and merges all text nodes that are close to each other.
354
+
355
+ This is useful for text extraction.
356
+ Use it when you need to strip HTML tags and merge "dangling" text.
357
+
358
+ Examples
359
+ --------
360
+
361
+ >>> tree = HTMLParser("<div><p><strong>J</strong>ohn</p><p>Doe</p></div>")
362
+ >>> node = tree.css_first('div')
363
+ >>> tree.unwrap_tags(["strong"])
364
+ >>> tree.text(deep=True, separator=" ", strip=True)
365
+ "J ohn Doe" # Text extraction produces an extra space because the strong tag was removed.
366
+ >>> node.merge_text_nodes()
367
+ >>> tree.text(deep=True, separator=" ", strip=True)
368
+ "John Doe"
369
+ """
370
+ return self.root.merge_text_nodes()
371
+ @staticmethod
372
+ cdef HTMLParser from_tree(
373
+ myhtml_tree_t * tree, bytes raw_html, bint detect_encoding, bint use_meta_tags, str decode_errors,
374
+ myencoding_t encoding
375
+ ):
376
+ obj = <HTMLParser> HTMLParser.__new__(HTMLParser)
377
+ obj.html_tree = tree
378
+ obj.raw_html = raw_html
379
+ obj.detect_encoding = detect_encoding
380
+ obj.use_meta_tags = use_meta_tags
381
+ obj.decode_errors = decode_errors
382
+ obj._encoding = encoding
383
+ obj.cached_script_texts = None
384
+ obj.cached_script_srcs = None
385
+ return obj
386
+
387
+
388
+ def clone(self):
389
+ """Clone the current tree."""
390
+ cdef myhtml_t* myhtml
391
+ cdef mystatus_t status
392
+ cdef myhtml_tree_t* html_tree
393
+ cdef myhtml_tree_node_t* node
394
+
395
+ with nogil:
396
+ myhtml = myhtml_create()
397
+ status = myhtml_init(myhtml, MyHTML_OPTIONS_DEFAULT, 1, 0)
398
+
399
+ if status != 0:
400
+ raise RuntimeError("Can't init MyHTML object.")
401
+
402
+ with nogil:
403
+ html_tree = myhtml_tree_create()
404
+ status = myhtml_tree_init(html_tree, myhtml)
405
+
406
+ if status != 0:
407
+ raise RuntimeError("Can't init MyHTML Tree object.")
408
+
409
+ node = myhtml_node_clone_deep(html_tree, self.html_tree.node_html)
410
+ myhtml_tree_node_add_child(html_tree.document, node)
411
+ html_tree.node_html = node
412
+
413
+ cls = HTMLParser.from_tree(
414
+ html_tree,
415
+ self.raw_html,
416
+ self.detect_encoding,
417
+ self.use_meta_tags,
418
+ self.decode_errors,
419
+ self._encoding
420
+ )
421
+ return cls
422
+
423
+ def __dealloc__(self):
424
+ cdef myhtml_t* myhtml
425
+
426
+ if self.html_tree != NULL:
427
+ myhtml = self.html_tree.myhtml
428
+ myhtml_tree_destroy(self.html_tree)
429
+ if myhtml != NULL:
430
+ myhtml_destroy(myhtml)
431
+
432
+ def __repr__(self):
433
+ return '<HTMLParser chars=%s>' % len(self.root.html)
selectolax/py.typed ADDED
File without changes
selectolax/utils.pxi ADDED
@@ -0,0 +1,107 @@
1
+ from typing import Literal, Optional, Union, Type
2
+
3
+ MAX_HTML_INPUT_SIZE = 250e+7
4
+
5
+ ParserCls = Union[Type["HTMLParser"], Type["LexborHTMLParser"]]
6
+ Parser = Union["HTMLParser", "LexborHTMLParser"]
7
+
8
+
9
+ def preprocess_input(html, decode_errors='ignore'):
10
+ if isinstance(html, (str, unicode)):
11
+ bytes_html = html.encode('UTF-8', errors=decode_errors)
12
+ elif isinstance(html, bytes):
13
+ bytes_html = html
14
+ else:
15
+ raise TypeError("Expected a string, but %s found" % type(html).__name__)
16
+ html_len = len(bytes_html)
17
+ if html_len > MAX_HTML_INPUT_SIZE:
18
+ raise ValueError("The specified HTML input is too large to be processed (%d bytes)" % html_len)
19
+ return bytes_html, html_len
20
+
21
+
22
+ def do_create_tag(tag: str, parser_cls: ParserCls):
23
+ if not tag:
24
+ raise ValueError("Tag name cannot be empty")
25
+ return do_parse_fragment(f"<{tag}></{tag}>", parser_cls)[0]
26
+
27
+
28
+ def get_fragment_type(
29
+ html: str,
30
+ parser_cls: ParserCls,
31
+ tree: Optional[Parser] = None,
32
+ ) -> Literal["document", "fragment", "head", "body", "head_and_body", "document_no_head", "document_no_body", "document_no_head_no_body"]:
33
+ if not tree:
34
+ tree = parser_cls(html)
35
+
36
+ import re
37
+ html_re = re.compile(r"<html|<body|<head(?!er)", re.IGNORECASE)
38
+
39
+ has_html = False
40
+ has_head = False
41
+ has_body = False
42
+ for match in html_re.finditer(html):
43
+ if match[0] == "<html":
44
+ has_html = True
45
+ elif match[0] == "<head":
46
+ has_head = True
47
+ elif match[0] == "<body":
48
+ has_body = True
49
+
50
+ if has_html and has_head and has_body:
51
+ break
52
+
53
+ if has_html and has_head and has_body:
54
+ return "document"
55
+ elif has_html and not has_head and has_body:
56
+ return "document_no_head"
57
+ elif has_html and has_head and not has_body:
58
+ return "document_no_body"
59
+ elif has_html and not has_head and not has_body:
60
+ return "document_no_head_no_body"
61
+ elif has_head and not has_body:
62
+ return "head"
63
+ elif not has_head and has_body:
64
+ return "body"
65
+ elif has_head and has_body:
66
+ return "head_and_body"
67
+ else:
68
+ return "fragment"
69
+
70
+
71
+ def do_parse_fragment(html: str, parser_cls: ParserCls):
72
+ """
73
+ Given HTML, parse it into a list of Nodes, such that the nodes
74
+ correspond to the given HTML.
75
+
76
+ For contrast, HTMLParser adds `<html>`, `<head>`, and `<body>` tags
77
+ if they are missing. This function does not add these tags.
78
+ """
79
+ html = html.strip()
80
+ tree = parser_cls(html)
81
+ frag_type = get_fragment_type(html, parser_cls, tree)
82
+
83
+ if frag_type == "document":
84
+ return [tree.root]
85
+ if frag_type == "document_no_head":
86
+ tree.head.decompose(recursive=True)
87
+ return [tree.root]
88
+ if frag_type == "document_no_body":
89
+ tree.body.decompose(recursive=True)
90
+ return [tree.root]
91
+ if frag_type == "document_no_head_no_body":
92
+ tree.head.decompose(recursive=True)
93
+ tree.body.decompose(recursive=True)
94
+ return [tree.root]
95
+ elif frag_type == "head":
96
+ tree.body.decompose(recursive=True)
97
+ return [tree.head]
98
+ elif frag_type == "body":
99
+ tree.head.decompose(recursive=True)
100
+ return [tree.body]
101
+ elif frag_type == "head_and_body":
102
+ return [tree.head, tree.body]
103
+ else:
104
+ return [
105
+ *tree.head.iter(include_text=True),
106
+ *tree.body.iter(include_text=True),
107
+ ]
@@ -0,0 +1,10 @@
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2018-2025, Artem Golubin
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.