selectolax 0.3.34__cp314-cp314t-win_arm64.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/lexbor.pyx ADDED
@@ -0,0 +1,388 @@
1
+ from cpython.bool cimport bool
2
+ from cpython.exc cimport PyErr_SetObject
3
+
4
+ _ENCODING = 'UTF-8'
5
+
6
+ include "base.pxi"
7
+ include "utils.pxi"
8
+ include "lexbor/attrs.pxi"
9
+ include "lexbor/node.pxi"
10
+ include "lexbor/selection.pxi"
11
+ include "lexbor/util.pxi"
12
+
13
+ # We don't inherit from HTMLParser here, because it also includes all the C code from Modest.
14
+
15
+ cdef class LexborHTMLParser:
16
+ """The lexbor HTML parser.
17
+
18
+ Use this class to parse raw HTML.
19
+
20
+ This parser mimics most of the stuff from ``HTMLParser`` but not inherits it directly.
21
+
22
+ Parameters
23
+ ----------
24
+
25
+ html : str (unicode) or bytes
26
+ """
27
+ def __init__(self, html):
28
+ cdef size_t html_len
29
+ cdef object bytes_html
30
+ bytes_html, html_len = preprocess_input(html)
31
+ self._parse_html(bytes_html, html_len)
32
+ self.raw_html = bytes_html
33
+ self._selector = None
34
+
35
+ @property
36
+ def selector(self):
37
+ if self._selector is None:
38
+ self._selector = LexborCSSSelector()
39
+ return self._selector
40
+
41
+ cdef int _parse_html(self, char *html, size_t html_len) except -1:
42
+ cdef lxb_status_t status
43
+
44
+ with nogil:
45
+ self.document = lxb_html_document_create()
46
+
47
+ if self.document == NULL:
48
+ PyErr_SetObject(SelectolaxError, "Failed to initialize object for HTML Document.")
49
+ return -1
50
+
51
+ with nogil:
52
+ status = lxb_html_document_parse(self.document, <lxb_char_t *> html, html_len)
53
+
54
+ if status != 0x0000:
55
+ PyErr_SetObject(SelectolaxError, "Can't parse HTML.")
56
+ return -1
57
+
58
+ if self.document == NULL:
59
+ PyErr_SetObject(RuntimeError, "document is NULL even after html was parsed correctly")
60
+ return -1
61
+ return 0
62
+
63
+ def __dealloc__(self):
64
+ if self.document != NULL:
65
+ lxb_html_document_destroy(self.document)
66
+
67
+ def __repr__(self):
68
+ return '<LexborHTMLParser chars=%s>' % len(self.root.html)
69
+
70
+ @property
71
+ def root(self):
72
+ """Returns root node."""
73
+ if self.document == NULL:
74
+ return None
75
+ return LexborNode.new(<lxb_dom_node_t *> lxb_dom_document_root(&self.document.dom_document), self)
76
+
77
+ @property
78
+ def body(self):
79
+ """Returns document body."""
80
+ cdef lxb_html_body_element_t* body
81
+ body = lxb_html_document_body_element_noi(self.document)
82
+ if body == NULL:
83
+ return None
84
+ return LexborNode.new(<lxb_dom_node_t *> body, self)
85
+
86
+ @property
87
+ def head(self):
88
+ """Returns document head."""
89
+ cdef lxb_html_head_element_t* head
90
+ head = lxb_html_document_head_element_noi(self.document)
91
+ if head == NULL:
92
+ return None
93
+ return LexborNode.new(<lxb_dom_node_t *> head, self)
94
+
95
+ def tags(self, str name):
96
+ """Returns a list of tags that match specified name.
97
+
98
+ Parameters
99
+ ----------
100
+ name : str (e.g. div)
101
+
102
+ """
103
+
104
+ if not name:
105
+ raise ValueError("Tag name cannot be empty")
106
+ if len(name) > 100:
107
+ raise ValueError("Tag name is too long")
108
+
109
+ cdef lxb_dom_collection_t* collection = NULL
110
+ cdef lxb_status_t status
111
+ pybyte_name = name.encode('UTF-8')
112
+
113
+ result = list()
114
+ collection = lxb_dom_collection_make(&self.document.dom_document, 128)
115
+
116
+ if collection == NULL:
117
+ return result
118
+ status = lxb_dom_elements_by_tag_name(
119
+ <lxb_dom_element_t *> self.document,
120
+ collection,
121
+ <lxb_char_t *> pybyte_name,
122
+ len(pybyte_name)
123
+ )
124
+ if status != 0x0000:
125
+ lxb_dom_collection_destroy(collection, <bint> True)
126
+ raise SelectolaxError("Can't locate elements.")
127
+
128
+ for i in range(lxb_dom_collection_length_noi(collection)):
129
+ node = LexborNode.new(
130
+ <lxb_dom_node_t*> lxb_dom_collection_element_noi(collection, i),
131
+ self
132
+ )
133
+ result.append(node)
134
+ lxb_dom_collection_destroy(collection, <bint> True)
135
+ return result
136
+
137
+ def text(self, bool deep=True, str separator='', bool strip=False):
138
+ """Returns the text of the node including text of all its child nodes.
139
+
140
+ Parameters
141
+ ----------
142
+ strip : bool, default False
143
+ If true, calls ``str.strip()`` on each text part to remove extra white spaces.
144
+ separator : str, default ''
145
+ The separator to use when joining text from different nodes.
146
+ deep : bool, default True
147
+ If True, includes text from all child nodes.
148
+
149
+ Returns
150
+ -------
151
+ text : str
152
+
153
+ """
154
+ if self.body is None:
155
+ return ""
156
+ return self.body.text(deep=deep, separator=separator, strip=strip)
157
+
158
+ @property
159
+ def html(self):
160
+ """Return HTML representation of the page."""
161
+ if self.document == NULL:
162
+ return None
163
+ node = LexborNode.new(<lxb_dom_node_t *> &self.document.dom_document, self)
164
+ return node.html
165
+
166
+ def css(self, str query):
167
+ """A CSS selector.
168
+
169
+ Matches pattern `query` against HTML tree.
170
+ `CSS selectors reference <https://www.w3schools.com/cssref/css_selectors.asp>`_.
171
+
172
+ Special selectors:
173
+
174
+ - parser.css('p:lexbor-contains("awesome" i)') -- case-insensitive contains
175
+ - parser.css('p:lexbor-contains("awesome")') -- case-sensitive contains
176
+
177
+ Parameters
178
+ ----------
179
+ query : str
180
+ CSS selector (e.g. "div > :nth-child(2n+1):not(:has(a))").
181
+
182
+ Returns
183
+ -------
184
+ selector : list of `Node` objects
185
+ """
186
+ return self.root.css(query)
187
+
188
+ def css_first(self, str query, default=None, strict=False):
189
+ """Same as `css` but returns only the first match.
190
+
191
+ Parameters
192
+ ----------
193
+
194
+ query : str
195
+ default : bool, default None
196
+ Default value to return if there is no match.
197
+ strict: bool, default True
198
+ Set to True if you want to check if there is strictly only one match in the document.
199
+
200
+
201
+ Returns
202
+ -------
203
+ selector : `LexborNode` object
204
+ """
205
+ return self.root.css_first(query, default, strict)
206
+
207
+ def strip_tags(self, list tags, bool recursive = False):
208
+ """Remove specified tags from the node.
209
+
210
+ Parameters
211
+ ----------
212
+ tags : list of str
213
+ List of tags to remove.
214
+ recursive : bool, default True
215
+ Whenever to delete all its child nodes
216
+
217
+ Examples
218
+ --------
219
+
220
+ >>> tree = LexborHTMLParser('<html><head></head><body><script></script><div>Hello world!</div></body></html>')
221
+ >>> tags = ['head', 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes']
222
+ >>> tree.strip_tags(tags)
223
+ >>> tree.html
224
+ '<html><body><div>Hello world!</div></body></html>'
225
+
226
+ """
227
+ cdef lxb_dom_collection_t* collection = NULL
228
+ cdef lxb_status_t status
229
+
230
+ for tag in tags:
231
+ pybyte_name = tag.encode('UTF-8')
232
+
233
+ collection = lxb_dom_collection_make(&self.document.dom_document, 128)
234
+
235
+ if collection == NULL:
236
+ raise SelectolaxError("Can't initialize DOM collection.")
237
+
238
+ status = lxb_dom_elements_by_tag_name(
239
+ <lxb_dom_element_t *> self.document,
240
+ collection,
241
+ <lxb_char_t *> pybyte_name,
242
+ len(pybyte_name)
243
+ )
244
+ if status != 0x0000:
245
+ lxb_dom_collection_destroy(collection, <bint> True)
246
+ raise SelectolaxError("Can't locate elements.")
247
+
248
+ for i in range(lxb_dom_collection_length_noi(collection)):
249
+ if recursive:
250
+ lxb_dom_node_destroy_deep(<lxb_dom_node_t*> lxb_dom_collection_element_noi(collection, i))
251
+ else:
252
+ lxb_dom_node_destroy(<lxb_dom_node_t *> lxb_dom_collection_element_noi(collection, i))
253
+ lxb_dom_collection_destroy(collection, <bint> True)
254
+
255
+ def select(self, query=None):
256
+ """Select nodes give a CSS selector.
257
+
258
+ Works similarly to the ``css`` method, but supports chained filtering and extra features.
259
+
260
+ Parameters
261
+ ----------
262
+ query : str or None
263
+ The CSS selector to use when searching for nodes.
264
+
265
+ Returns
266
+ -------
267
+ selector : The `Selector` class.
268
+ """
269
+ cdef LexborNode node
270
+ node = self.root
271
+ if node:
272
+ return LexborSelector(node, query)
273
+
274
+ def any_css_matches(self, tuple selectors):
275
+ """Returns True if any of the specified CSS selectors matches a node."""
276
+ return self.root.any_css_matches(selectors)
277
+
278
+ def scripts_contain(self, str query):
279
+ """Returns True if any of the script tags contain specified text.
280
+
281
+ Caches script tags on the first call to improve performance.
282
+
283
+ Parameters
284
+ ----------
285
+ query : str
286
+ The query to check.
287
+
288
+ """
289
+ return self.root.scripts_contain(query)
290
+
291
+ def script_srcs_contain(self, tuple queries):
292
+ """Returns True if any of the script SRCs attributes contain on of the specified text.
293
+
294
+ Caches values on the first call to improve performance.
295
+
296
+ Parameters
297
+ ----------
298
+ queries : tuple of str
299
+
300
+ """
301
+ return self.root.script_srcs_contain(queries)
302
+
303
+ def css_matches(self, str selector):
304
+ return self.root.css_matches(selector)
305
+
306
+ def merge_text_nodes(self):
307
+ """Iterates over all text nodes and merges all text nodes that are close to each other.
308
+
309
+ This is useful for text extraction.
310
+ Use it when you need to strip HTML tags and merge "dangling" text.
311
+
312
+ Examples
313
+ --------
314
+
315
+ >>> tree = LexborHTMLParser("<div><p><strong>J</strong>ohn</p><p>Doe</p></div>")
316
+ >>> node = tree.css_first('div')
317
+ >>> tree.unwrap_tags(["strong"])
318
+ >>> tree.text(deep=True, separator=" ", strip=True)
319
+ "J ohn Doe" # Text extraction produces an extra space because the strong tag was removed.
320
+ >>> node.merge_text_nodes()
321
+ >>> tree.text(deep=True, separator=" ", strip=True)
322
+ "John Doe"
323
+ """
324
+ return self.root.merge_text_nodes()
325
+
326
+ @staticmethod
327
+ cdef LexborHTMLParser from_document(lxb_html_document_t *document, bytes raw_html):
328
+ obj = <LexborHTMLParser> LexborHTMLParser.__new__(LexborHTMLParser)
329
+ obj.document = document
330
+ obj.raw_html = raw_html
331
+ obj.cached_script_texts = None
332
+ obj.cached_script_srcs = None
333
+ obj._selector = None
334
+ return obj
335
+
336
+ def clone(self):
337
+ """Clone the current tree."""
338
+ cdef lxb_html_document_t* cloned_document
339
+ cdef lxb_dom_node_t* cloned_node
340
+ cdef LexborHTMLParser cls
341
+
342
+ with nogil:
343
+ cloned_document = lxb_html_document_create()
344
+
345
+ if cloned_document == NULL:
346
+ raise SelectolaxError("Can't create a new document")
347
+
348
+ cloned_document.ready_state = LXB_HTML_DOCUMENT_READY_STATE_COMPLETE
349
+
350
+ with nogil:
351
+ cloned_node = lxb_dom_document_import_node(
352
+ &cloned_document.dom_document,
353
+ <lxb_dom_node_t *> lxb_dom_document_root(&self.document.dom_document),
354
+ <bint> True
355
+ )
356
+
357
+ if cloned_node == NULL:
358
+ raise SelectolaxError("Can't create a new document")
359
+
360
+ with nogil:
361
+ lxb_dom_node_insert_child(<lxb_dom_node_t * > cloned_document, cloned_node)
362
+
363
+ cls = LexborHTMLParser.from_document(cloned_document, self.raw_html)
364
+ return cls
365
+
366
+ def unwrap_tags(self, list tags, delete_empty = False):
367
+ """Unwraps specified tags from the HTML tree.
368
+
369
+ Works the same as the ``unwrap`` method, but applied to a list of tags.
370
+
371
+ Parameters
372
+ ----------
373
+ tags : list
374
+ List of tags to remove.
375
+ delete_empty : bool
376
+ Whenever to delete empty tags.
377
+
378
+ Examples
379
+ --------
380
+
381
+ >>> tree = LexborHTMLParser("<div><a href="">Hello</a> <i>world</i>!</div>")
382
+ >>> tree.body.unwrap_tags(['i','a'])
383
+ >>> tree.body.html
384
+ '<body><div>Hello world!</div></body>'
385
+ """
386
+ # faster to check if the document is empty which should determine if we have a root
387
+ if self.document != NULL:
388
+ self.root.unwrap_tags(tags, delete_empty=delete_empty)