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