selectolax 0.3.30__cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_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,446 @@
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 (status code: %d)" % status)
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
+ try:
151
+ node = Node()
152
+ node._init(self.html_tree.node_html, self)
153
+ return node
154
+ except Exception:
155
+ # If Node creation or initialization fails, return None
156
+ return None
157
+ return None
158
+
159
+ @property
160
+ def head(self):
161
+ """Returns head node."""
162
+ cdef myhtml_tree_node_t* head
163
+ head = myhtml_tree_get_node_head(self.html_tree)
164
+
165
+ if head != NULL:
166
+ node = Node()
167
+ node._init(head, self)
168
+ return node
169
+ return None
170
+
171
+ @property
172
+ def body(self):
173
+ """Returns document body."""
174
+ cdef myhtml_tree_node_t* body
175
+ body = myhtml_tree_get_node_body(self.html_tree)
176
+
177
+ if body != NULL:
178
+ node = Node()
179
+ node._init(body, self)
180
+ return node
181
+
182
+ return None
183
+
184
+ def tags(self, str name):
185
+ """Returns a list of tags that match specified name.
186
+
187
+ Parameters
188
+ ----------
189
+ name : str (e.g. div)
190
+
191
+ """
192
+ # Validate tag name
193
+ if not name:
194
+ raise ValueError("Tag name cannot be empty")
195
+ if len(name) > 100: # Reasonable limit for tag names
196
+ raise ValueError("Tag name is too long")
197
+
198
+ cdef myhtml_collection_t* collection = NULL
199
+ pybyte_name = name.encode('UTF-8')
200
+ cdef mystatus_t status = 0;
201
+
202
+ result = list()
203
+ collection = myhtml_get_nodes_by_name(self.html_tree, NULL, pybyte_name, len(pybyte_name), &status)
204
+
205
+ if collection == NULL:
206
+ return result
207
+
208
+ if status == 0:
209
+ for i in range(collection.length):
210
+ node = Node()
211
+ node._init(collection.list[i], self)
212
+ result.append(node)
213
+
214
+ myhtml_collection_destroy(collection)
215
+
216
+ return result
217
+
218
+ def text(self, bool deep=True, str separator='', bool strip=False):
219
+ """Returns the text of the node including text of all its child nodes.
220
+
221
+ Parameters
222
+ ----------
223
+ strip : bool, default False
224
+ If true, calls ``str.strip()`` on each text part to remove extra white spaces.
225
+ separator : str, default ''
226
+ The separator to use when joining text from different nodes.
227
+ deep : bool, default True
228
+ If True, includes text from all child nodes.
229
+
230
+ Returns
231
+ -------
232
+ text : str
233
+
234
+ """
235
+ if not self.body:
236
+ return ""
237
+ return self.body.text(deep=deep, separator=separator, strip=strip)
238
+
239
+ def strip_tags(self, list tags, bool recursive = False):
240
+ """Remove specified tags from the node.
241
+
242
+ Parameters
243
+ ----------
244
+ tags : list of str
245
+ List of tags to remove.
246
+ recursive : bool, default True
247
+ Whenever to delete all its child nodes
248
+
249
+ Examples
250
+ --------
251
+
252
+ >>> tree = HTMLParser('<html><head></head><body><script></script><div>Hello world!</div></body></html>')
253
+ >>> tags = ['head', 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes']
254
+ >>> tree.strip_tags(tags)
255
+ >>> tree.html
256
+ '<html><body><div>Hello world!</div></body></html>'
257
+
258
+ """
259
+ cdef myhtml_collection_t* collection = NULL
260
+
261
+ cdef mystatus_t status = 0;
262
+
263
+ for tag in tags:
264
+ pybyte_name = tag.encode('UTF-8')
265
+ collection = myhtml_get_nodes_by_name(self.html_tree, NULL, pybyte_name, len(pybyte_name), &status)
266
+
267
+ if collection == NULL:
268
+ continue
269
+
270
+ if status != 0:
271
+ continue
272
+
273
+ for i in range(collection.length):
274
+ if recursive:
275
+ myhtml_node_delete_recursive(collection.list[i])
276
+ else:
277
+ myhtml_node_delete(collection.list[i])
278
+
279
+ myhtml_collection_destroy(collection)
280
+
281
+
282
+ def unwrap_tags(self, list tags, delete_empty : bool = False):
283
+ """Unwraps specified tags from the HTML tree.
284
+
285
+ Works the same as th `unwrap` method, but applied to a list of tags.
286
+
287
+ Parameters
288
+ ----------
289
+ tags : list
290
+ List of tags to remove.
291
+ delete_empty : bool, default False
292
+ If True, removes empty tags.
293
+
294
+ Examples
295
+ --------
296
+
297
+ >>> tree = HTMLParser("<div><a href="">Hello</a> <i>world</i>!</div>")
298
+ >>> tree.head.unwrap_tags(['i','a'])
299
+ >>> tree.head.html
300
+ '<body><div>Hello world!</div></body>'
301
+ """
302
+ if self.root is not None:
303
+ self.root.unwrap_tags(tags, delete_empty=delete_empty)
304
+
305
+ @property
306
+ def html(self):
307
+ """Return HTML representation of the page."""
308
+ if self.html_tree and self.html_tree.document:
309
+ node = Node()
310
+ node._init(self.html_tree.document, self)
311
+ return node.html
312
+ return None
313
+
314
+ def select(self, query=None):
315
+ """Select nodes given a CSS selector.
316
+
317
+ Works similarly to the ``css`` method, but supports chained filtering and extra features.
318
+
319
+ Parameters
320
+ ----------
321
+ query : str or None
322
+ The CSS selector to use when searching for nodes.
323
+
324
+ Returns
325
+ -------
326
+ selector : The `Selector` class.
327
+ """
328
+ cdef Node node
329
+ node = self.root
330
+ if node:
331
+ return Selector(node, query)
332
+
333
+ def any_css_matches(self, tuple selectors):
334
+ """Returns True if any of the specified CSS selectors matches a node."""
335
+ return self.root.any_css_matches(selectors)
336
+
337
+ def scripts_contain(self, str query):
338
+ """Returns True if any of the script tags contain specified text.
339
+
340
+ Caches script tags on the first call to improve performance.
341
+
342
+ Parameters
343
+ ----------
344
+ query : str
345
+ The query to check.
346
+
347
+ """
348
+ return self.root.scripts_contain(query)
349
+
350
+ def script_srcs_contain(self, tuple queries):
351
+ """Returns True if any of the script SRCs attributes contain on of the specified text.
352
+
353
+ Caches values on the first call to improve performance.
354
+
355
+ Parameters
356
+ ----------
357
+ queries : tuple of str
358
+
359
+ """
360
+ return self.root.script_srcs_contain(queries)
361
+
362
+ def css_matches(self, str selector):
363
+ return self.root.css_matches(selector)
364
+ def merge_text_nodes(self):
365
+ """Iterates over all text nodes and merges all text nodes that are close to each other.
366
+
367
+ This is useful for text extraction.
368
+ Use it when you need to strip HTML tags and merge "dangling" text.
369
+
370
+ Examples
371
+ --------
372
+
373
+ >>> tree = HTMLParser("<div><p><strong>J</strong>ohn</p><p>Doe</p></div>")
374
+ >>> node = tree.css_first('div')
375
+ >>> tree.unwrap_tags(["strong"])
376
+ >>> tree.text(deep=True, separator=" ", strip=True)
377
+ "J ohn Doe" # Text extraction produces an extra space because the strong tag was removed.
378
+ >>> node.merge_text_nodes()
379
+ >>> tree.text(deep=True, separator=" ", strip=True)
380
+ "John Doe"
381
+ """
382
+ return self.root.merge_text_nodes()
383
+ @staticmethod
384
+ cdef HTMLParser from_tree(
385
+ myhtml_tree_t * tree, bytes raw_html, bint detect_encoding, bint use_meta_tags, str decode_errors,
386
+ myencoding_t encoding
387
+ ):
388
+ obj = <HTMLParser> HTMLParser.__new__(HTMLParser)
389
+ obj.html_tree = tree
390
+ obj.raw_html = raw_html
391
+ obj.detect_encoding = detect_encoding
392
+ obj.use_meta_tags = use_meta_tags
393
+ obj.decode_errors = decode_errors
394
+ obj._encoding = encoding
395
+ obj.cached_script_texts = None
396
+ obj.cached_script_srcs = None
397
+ return obj
398
+
399
+
400
+ def clone(self):
401
+ """Clone the current tree."""
402
+ cdef myhtml_t* myhtml
403
+ cdef mystatus_t status
404
+ cdef myhtml_tree_t* html_tree
405
+ cdef myhtml_tree_node_t* node
406
+
407
+ with nogil:
408
+ myhtml = myhtml_create()
409
+ status = myhtml_init(myhtml, MyHTML_OPTIONS_DEFAULT, 1, 0)
410
+
411
+ if status != 0:
412
+ raise RuntimeError("Can't init MyHTML object.")
413
+
414
+ with nogil:
415
+ html_tree = myhtml_tree_create()
416
+ status = myhtml_tree_init(html_tree, myhtml)
417
+
418
+ if status != 0:
419
+ raise RuntimeError("Can't init MyHTML Tree object.")
420
+
421
+ node = myhtml_node_clone_deep(html_tree, self.html_tree.node_html)
422
+ myhtml_tree_node_add_child(html_tree.document, node)
423
+ html_tree.node_html = node
424
+
425
+ cls = HTMLParser.from_tree(
426
+ html_tree,
427
+ self.raw_html,
428
+ self.detect_encoding,
429
+ self.use_meta_tags,
430
+ self.decode_errors,
431
+ self._encoding
432
+ )
433
+ return cls
434
+
435
+ def __dealloc__(self):
436
+ cdef myhtml_t* myhtml
437
+
438
+ if self.html_tree != NULL:
439
+ myhtml = self.html_tree.myhtml
440
+ myhtml_tree_destroy(self.html_tree)
441
+ self.html_tree = NULL # Prevent double-free
442
+ if myhtml != NULL:
443
+ myhtml_destroy(myhtml)
444
+
445
+ def __repr__(self):
446
+ 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
+ ]