selectolax 0.3.30__cp310-cp310-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.

@@ -0,0 +1,987 @@
1
+ cimport cython
2
+
3
+ from libc.stdlib cimport free
4
+ from libc.stdlib cimport malloc
5
+ from libc.stdlib cimport realloc
6
+ from libc.string cimport memcpy
7
+
8
+ DEF _STACK_SIZE = 100
9
+ DEF _ENCODING = 'UTF-8'
10
+
11
+ @cython.final
12
+ cdef class Stack:
13
+ def __cinit__(self, size_t capacity=25):
14
+ self.capacity = capacity
15
+ self.top = 0
16
+ self._stack = <myhtml_tree_node_t**> malloc(capacity * sizeof(myhtml_tree_node_t))
17
+ if self._stack == NULL:
18
+ raise MemoryError("Failed to allocate memory for stack")
19
+
20
+ def __dealloc__(self):
21
+ free(self._stack)
22
+
23
+ cdef bint is_empty(self):
24
+ return self.top <= 0
25
+
26
+ cdef push(self, myhtml_tree_node_t* res):
27
+ if self.top >= self.capacity:
28
+ self.resize()
29
+ self._stack[self.top] = res
30
+ self.top += 1
31
+
32
+ cdef myhtml_tree_node_t * pop(self):
33
+ self.top = self.top - 1
34
+ return self._stack[self.top]
35
+
36
+ cdef resize(self):
37
+ self.capacity *= 2
38
+ self._stack = <myhtml_tree_node_t**> realloc(<void*> self._stack, self.capacity * sizeof(myhtml_tree_node_t))
39
+
40
+
41
+ cdef class _Attributes:
42
+ """A dict-like object that represents attributes."""
43
+ cdef myhtml_tree_node_t * node
44
+ cdef unicode decode_errors
45
+
46
+ @staticmethod
47
+ cdef _Attributes create(myhtml_tree_node_t *node, unicode decode_errors):
48
+ obj = <_Attributes>_Attributes.__new__(_Attributes)
49
+ obj.node = node
50
+ obj.decode_errors = decode_errors
51
+ return obj
52
+
53
+ def __iter__(self):
54
+ cdef myhtml_tree_attr_t *attr = myhtml_node_attribute_first(self.node)
55
+ while attr:
56
+ if attr.key.data == NULL:
57
+ attr = attr.next
58
+ continue
59
+ key = attr.key.data.decode(_ENCODING, self.decode_errors)
60
+ attr = attr.next
61
+ yield key
62
+
63
+ def __setitem__(self, str key, value):
64
+ value = str(value)
65
+ bytes_key = key.encode(_ENCODING)
66
+ bytes_value = value.encode(_ENCODING)
67
+ myhtml_attribute_remove_by_key(self.node, <char*>bytes_key, len(bytes_key))
68
+ myhtml_attribute_add(self.node, <char*>bytes_key, len(bytes_key), <char*>bytes_value, len(bytes_value),
69
+ MyENCODING_UTF_8)
70
+
71
+ def __delitem__(self, key):
72
+ try:
73
+ self.__getitem__(key)
74
+ except KeyError:
75
+ raise KeyError(key)
76
+ bytes_key = key.encode(_ENCODING)
77
+ myhtml_attribute_remove_by_key(self.node, <char*>bytes_key, len(bytes_key))
78
+
79
+ def __getitem__(self, str key):
80
+ bytes_key = key.encode(_ENCODING)
81
+ cdef myhtml_tree_attr_t * attr = myhtml_attribute_by_key(self.node, <char*>bytes_key, len(bytes_key))
82
+ if attr != NULL:
83
+ if attr.value.data != NULL:
84
+ return attr.value.data.decode(_ENCODING, self.decode_errors)
85
+ elif attr.key.data != NULL:
86
+ return None
87
+ raise KeyError(key)
88
+
89
+ def __len__(self):
90
+ return len(list(self.__iter__()))
91
+
92
+ def keys(self):
93
+ return self.__iter__()
94
+
95
+ def items(self):
96
+ for key in self.__iter__():
97
+ yield key, self[key]
98
+
99
+ def values(self):
100
+ for key in self.__iter__():
101
+ yield self[key]
102
+
103
+ def get(self, key, default=None):
104
+ try:
105
+ return self[key]
106
+ except KeyError:
107
+ return default
108
+
109
+ def sget(self, key, default=""):
110
+ """Same as get, but returns empty strings instead of None values for empty attributes."""
111
+ try:
112
+ val = self[key]
113
+ if val is None:
114
+ val = ""
115
+ return val
116
+ except KeyError:
117
+ return default
118
+
119
+ def __contains__(self, key):
120
+ try:
121
+ self[key]
122
+ except KeyError:
123
+ return False
124
+ else:
125
+ return True
126
+
127
+ def __repr__(self):
128
+ cdef const char *c_text
129
+ c_text = myhtml_tag_name_by_id(self.node.tree, self.node.tag_id, NULL)
130
+ tag_name = c_text.decode(_ENCODING, 'ignore') if c_text != NULL else 'unknown'
131
+ return "<%s attributes, %s items>" % (tag_name, len(self))
132
+
133
+
134
+
135
+ ctypedef fused str_or_Node:
136
+ str
137
+ bytes
138
+ Node
139
+
140
+
141
+ cdef class Node:
142
+ """A class that represents HTML node (element)."""
143
+ cdef myhtml_tree_node_t *node
144
+ cdef public HTMLParser parser
145
+
146
+
147
+ cdef _init(self, myhtml_tree_node_t *node, HTMLParser parser):
148
+ # custom init, because __cinit__ doesn't accept C types
149
+ self.node = node
150
+ # Keep reference to the selector object, so myhtml structures will not be garbage collected prematurely
151
+ self.parser = parser
152
+
153
+ @property
154
+ def attributes(self):
155
+ """Get all attributes that belong to the current node.
156
+
157
+ The value of empty attributes is None.
158
+
159
+ Returns
160
+ -------
161
+ attributes : dictionary of all attributes.
162
+
163
+ Examples
164
+ --------
165
+
166
+ >>> tree = HTMLParser("<div data id='my_id'></div>")
167
+ >>> node = tree.css_first('div')
168
+ >>> node.attributes
169
+ {'data': None, 'id': 'my_id'}
170
+ """
171
+ cdef myhtml_tree_attr_t *attr = myhtml_node_attribute_first(self.node)
172
+ attributes = dict()
173
+
174
+ while attr:
175
+ if attr.key.data == NULL:
176
+ attr = attr.next
177
+ continue
178
+ key = attr.key.data.decode(_ENCODING, self.parser.decode_errors)
179
+ if attr.value.data:
180
+ value = attr.value.data.decode(_ENCODING, self.parser.decode_errors)
181
+ else:
182
+ value = None
183
+ attributes[key] = value
184
+
185
+ attr = attr.next
186
+
187
+ return attributes
188
+
189
+ @property
190
+ def attrs(self):
191
+ """A dict-like object that is similar to the ``attributes`` property, but operates directly on the Node data.
192
+
193
+ .. warning:: Use ``attributes`` instead, if you don't want to modify Node attributes.
194
+
195
+ Returns
196
+ -------
197
+ attributes : Attributes mapping object.
198
+
199
+ Examples
200
+ --------
201
+
202
+ >>> tree = HTMLParser("<div id='a'></div>")
203
+ >>> node = tree.css_first('div')
204
+ >>> node.attrs
205
+ <div attributes, 1 items>
206
+ >>> node.attrs['id']
207
+ 'a'
208
+ >>> node.attrs['foo'] = 'bar'
209
+ >>> del node.attrs['id']
210
+ >>> node.attributes
211
+ {'foo': 'bar'}
212
+ >>> node.attrs['id'] = 'new_id'
213
+ >>> node.html
214
+ '<div foo="bar" id="new_id"></div>'
215
+ """
216
+ cdef _Attributes attributes = _Attributes.create(self.node, self.parser.decode_errors)
217
+ return attributes
218
+
219
+ @property
220
+ def mem_id(self):
221
+ """Get the mem_id attribute of the node.
222
+
223
+ Returns
224
+ -------
225
+ text : int
226
+ """
227
+ return <size_t> self.node
228
+
229
+ @property
230
+ def id(self):
231
+ """Get the id attribute of the node.
232
+
233
+ Returns None if id does not set.
234
+
235
+ Returns
236
+ -------
237
+ text : str
238
+ """
239
+ cdef char* key = 'id'
240
+ cdef myhtml_tree_attr_t *attr
241
+ attr = myhtml_attribute_by_key(self.node, key, 2)
242
+ return None if attr == NULL else attr.value.data.decode(_ENCODING, self.parser.decode_errors)
243
+
244
+ def __hash__(self):
245
+ return self.mem_id
246
+
247
+ def text(self, bool deep=True, str separator='', bool strip=False):
248
+ """Returns the text of the node including text of all its child nodes.
249
+
250
+ Parameters
251
+ ----------
252
+ strip : bool, default False
253
+ If true, calls ``str.strip()`` on each text part to remove extra white spaces.
254
+ separator : str, default ''
255
+ The separator to use when joining text from different nodes.
256
+ deep : bool, default True
257
+ If True, includes text from all child nodes.
258
+
259
+ Returns
260
+ -------
261
+ text : str
262
+
263
+ """
264
+ text = ""
265
+ cdef const char* c_text
266
+ cdef myhtml_tree_node_t *node = self.node.child
267
+
268
+ if not deep:
269
+ if self.node.tag_id == MyHTML_TAG__TEXT:
270
+ c_text = myhtml_node_text(self.node, NULL)
271
+ if c_text != NULL:
272
+ node_text = c_text.decode(_ENCODING, self.parser.decode_errors)
273
+ text = append_text(text, node_text, separator, strip)
274
+
275
+ while node != NULL:
276
+ if node.tag_id == MyHTML_TAG__TEXT:
277
+ c_text = myhtml_node_text(node, NULL)
278
+ if c_text != NULL:
279
+ node_text = c_text.decode(_ENCODING, self.parser.decode_errors)
280
+ text = append_text(text, node_text, separator, strip)
281
+ node = node.next
282
+ else:
283
+ text = self._text_deep(self.node, separator=separator, strip=strip)
284
+ if separator and text and text.endswith(separator):
285
+ text = text[:-len(separator)]
286
+ return text
287
+
288
+ cdef inline _text_deep(self, myhtml_tree_node_t *node, separator='', strip=False):
289
+ text = ""
290
+ cdef Stack stack = Stack(_STACK_SIZE)
291
+ cdef myhtml_tree_node_t* current_node = NULL;
292
+
293
+ if node.tag_id == MyHTML_TAG__TEXT:
294
+ c_text = myhtml_node_text(node, NULL)
295
+ if c_text != NULL:
296
+ node_text = c_text.decode(_ENCODING, self.parser.decode_errors)
297
+ text = append_text(text, node_text, separator, strip)
298
+
299
+ if node.child == NULL:
300
+ return text
301
+
302
+ stack.push(node.child)
303
+
304
+ # Depth-first left-to-right tree traversal
305
+ while not stack.is_empty():
306
+ current_node = stack.pop()
307
+
308
+ if current_node != NULL:
309
+ if current_node.tag_id == MyHTML_TAG__TEXT:
310
+ c_text = myhtml_node_text(current_node, NULL)
311
+ if c_text != NULL:
312
+ node_text = c_text.decode(_ENCODING, self.parser.decode_errors)
313
+ text = append_text(text, node_text, separator, strip)
314
+
315
+ if current_node.next is not NULL:
316
+ stack.push(current_node.next)
317
+
318
+ if current_node.child is not NULL:
319
+ stack.push(current_node.child)
320
+
321
+ return text
322
+
323
+ def iter(self, include_text=False):
324
+ """Iterate over nodes on the current level.
325
+
326
+ Parameters
327
+ ----------
328
+ include_text : bool
329
+ If True, includes text nodes as well.
330
+
331
+ Yields
332
+ -------
333
+ node
334
+ """
335
+
336
+ cdef myhtml_tree_node_t *node = self.node.child
337
+ cdef Node next_node
338
+
339
+ while node != NULL:
340
+ if node.tag_id == MyHTML_TAG__TEXT and not include_text:
341
+ node = node.next
342
+ continue
343
+
344
+ next_node = Node()
345
+ next_node._init(node, self.parser)
346
+ yield next_node
347
+ node = node.next
348
+
349
+
350
+ def traverse(self, include_text=False):
351
+ """Iterate over all child and next nodes starting from the current level.
352
+
353
+ Parameters
354
+ ----------
355
+ include_text : bool
356
+ If True, includes text nodes as well.
357
+
358
+ Yields
359
+ -------
360
+ node
361
+ """
362
+ cdef Stack stack = Stack(_STACK_SIZE)
363
+ cdef myhtml_tree_node_t* current_node = NULL;
364
+ cdef Node next_node;
365
+
366
+ stack.push(self.node)
367
+
368
+ while not stack.is_empty():
369
+ current_node = stack.pop()
370
+ if current_node != NULL and not (current_node.tag_id == MyHTML_TAG__TEXT and not include_text):
371
+ next_node = Node()
372
+ next_node._init(current_node, self.parser)
373
+ yield next_node
374
+
375
+ if current_node.next is not NULL:
376
+ stack.push(current_node.next)
377
+
378
+ if current_node.child is not NULL:
379
+ stack.push(current_node.child)
380
+
381
+ @property
382
+ def tag(self):
383
+ """Return the name of the current tag (e.g. div, p, img).
384
+
385
+ Returns
386
+ -------
387
+ text : str
388
+ """
389
+ cdef const char *c_text
390
+ c_text = myhtml_tag_name_by_id(self.node.tree, self.node.tag_id, NULL)
391
+ text = None
392
+ if c_text:
393
+ text = c_text.decode(_ENCODING, self.parser.decode_errors)
394
+ return text
395
+
396
+ @property
397
+ def child(self):
398
+ """Return the child node."""
399
+ cdef Node node
400
+ if self.node.child:
401
+ node = Node()
402
+ node._init(self.node.child, self.parser)
403
+ return node
404
+ return None
405
+
406
+ @property
407
+ def parent(self):
408
+ """Return the parent node."""
409
+ cdef Node node
410
+ if self.node.parent:
411
+ node = Node()
412
+ node._init(self.node.parent, self.parser)
413
+ return node
414
+ return None
415
+
416
+ @property
417
+ def next(self):
418
+ """Return next node."""
419
+ cdef Node node
420
+ if self.node.next:
421
+ node = Node()
422
+ node._init(self.node.next, self.parser)
423
+ return node
424
+ return None
425
+
426
+ @property
427
+ def prev(self):
428
+ """Return previous node."""
429
+ cdef Node node
430
+ if self.node.prev:
431
+ node = Node()
432
+ node._init(self.node.prev, self.parser)
433
+ return node
434
+ return None
435
+
436
+ @property
437
+ def last_child(self):
438
+ """Return last child node."""
439
+ cdef Node node
440
+ if self.node.last_child:
441
+ node = Node()
442
+ node._init(self.node.last_child, self.parser)
443
+ return node
444
+ return None
445
+
446
+ @property
447
+ def html(self):
448
+ """Return HTML representation of the current node including all its child nodes.
449
+
450
+ Returns
451
+ -------
452
+ text : str
453
+ """
454
+ cdef mycore_string_raw_t c_str
455
+ c_str.data = NULL
456
+ c_str.length = 0
457
+ c_str.size = 0
458
+
459
+ cdef mystatus_t status
460
+ status = myhtml_serialization(self.node, &c_str)
461
+
462
+ if status == 0 and c_str.data:
463
+ html = c_str.data.decode(_ENCODING).replace('<-undef>', '')
464
+ free(c_str.data)
465
+ return html
466
+
467
+ return None
468
+
469
+ def css(self, str query):
470
+ """Evaluate CSS selector against current node and its child nodes."""
471
+ return find_nodes(self.parser, self.node, query)
472
+
473
+ def any_css_matches(self, tuple selectors):
474
+ """Returns True if any of CSS selectors matches a node"""
475
+ return find_matches(self.parser, self.node, selectors)
476
+
477
+ def css_matches(self, str selector):
478
+ """Returns True if CSS selector matches a node."""
479
+ return find_matches(self.parser, self.node, (selector, ))
480
+
481
+ def css_first(self, str query, default=None, bool strict=False):
482
+ """Evaluate CSS selector against current node and its child nodes."""
483
+ results = self.css(query)
484
+ n_results = len(results)
485
+
486
+ if n_results > 0:
487
+
488
+ if strict and n_results > 1:
489
+ raise ValueError("Expected 1 match, but found %s matches" % n_results)
490
+
491
+ return results[0]
492
+
493
+ return default
494
+
495
+ def decompose(self, bool recursive=True):
496
+ """Remove a Node from the tree.
497
+
498
+ Parameters
499
+ ----------
500
+ recursive : bool, default True
501
+ Whenever to delete all its child nodes
502
+
503
+ Examples
504
+ --------
505
+
506
+ >>> tree = HTMLParser(html)
507
+ >>> for tag in tree.css('script'):
508
+ >>> tag.decompose()
509
+
510
+ """
511
+ if recursive:
512
+ myhtml_node_delete_recursive(self.node)
513
+ else:
514
+ myhtml_node_delete(self.node)
515
+
516
+ def remove(self, bool recursive=True):
517
+ """An alias for the decompose method."""
518
+ self.decompose(recursive)
519
+
520
+ def unwrap(self, delete_empty = False):
521
+ """Replace node with whatever is inside this node.
522
+
523
+ Parameters
524
+ ----------
525
+ delete_empty : bool, default False
526
+ Whenever to delete empty tags.
527
+
528
+ Examples
529
+ --------
530
+
531
+ >>> tree = HTMLParser("<div>Hello <i>world</i>!</div>")
532
+ >>> tree.css_first('i').unwrap()
533
+ >>> tree.html
534
+ '<html><head></head><body><div>Hello world!</div></body></html>'
535
+
536
+ Note: by default, empty tags are ignored, set "delete_empty" to "True" to change this.
537
+ """
538
+ if self.node.child == NULL:
539
+ if delete_empty:
540
+ myhtml_node_delete(self.node)
541
+ return
542
+ cdef myhtml_tree_node_t* next_node;
543
+ cdef myhtml_tree_node_t* current_node;
544
+
545
+ if self.node.child.next != NULL:
546
+ current_node = self.node.child
547
+ next_node = current_node.next
548
+
549
+ while next_node != NULL:
550
+ next_node = current_node.next
551
+ myhtml_node_insert_before(self.node, current_node)
552
+ current_node = next_node
553
+ else:
554
+ myhtml_node_insert_before(self.node, self.node.child)
555
+ myhtml_node_delete(self.node)
556
+
557
+ def strip_tags(self, list tags, bool recursive = False):
558
+ """Remove specified tags from the HTML tree.
559
+
560
+ Parameters
561
+ ----------
562
+ tags : list
563
+ List of tags to remove.
564
+ recursive : bool, default True
565
+ Whenever to delete all its child nodes
566
+
567
+ Examples
568
+ --------
569
+
570
+ >>> tree = HTMLParser('<html><head></head><body><script></script><div>Hello world!</div></body></html>')
571
+ >>> tags = ['head', 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes']
572
+ >>> tree.strip_tags(tags)
573
+ >>> tree.html
574
+ '<html><body><div>Hello world!</div></body></html>'
575
+
576
+ """
577
+ for tag in tags:
578
+ for element in self.css(tag):
579
+ element.decompose(recursive=recursive)
580
+
581
+ def unwrap_tags(self, list tags, delete_empty = False):
582
+ """Unwraps specified tags from the HTML tree.
583
+
584
+ Works the same as the ``unwrap`` method, but applied to a list of tags.
585
+
586
+ Parameters
587
+ ----------
588
+ tags : list
589
+ List of tags to remove.
590
+ delete_empty : bool, default False
591
+ Whenever to delete empty tags.
592
+
593
+ Examples
594
+ --------
595
+
596
+ >>> tree = HTMLParser("<div><a href="">Hello</a> <i>world</i>!</div>")
597
+ >>> tree.body.unwrap_tags(['i','a'])
598
+ >>> tree.body.html
599
+ '<body><div>Hello world!</div></body>'
600
+
601
+ Note: by default, empty tags are ignored, set "delete_empty" to "True" to change this.
602
+ """
603
+
604
+ for tag in tags:
605
+ for element in self.css(tag):
606
+ element.unwrap(delete_empty)
607
+
608
+ def replace_with(self, str_or_Node value):
609
+ """Replace current Node with specified value.
610
+
611
+ Parameters
612
+ ----------
613
+ value : str, bytes or Node
614
+ The text or Node instance to replace the Node with.
615
+ When a text string is passed, it's treated as text. All HTML tags will be escaped.
616
+ Convert and pass the ``Node`` object when you want to work with HTML.
617
+ Does not clone the ``Node`` object.
618
+ All future changes to the passed ``Node`` object will also be taken into account.
619
+
620
+ Examples
621
+ --------
622
+
623
+ >>> tree = HTMLParser('<div>Get <img src="" alt="Laptop"></div>')
624
+ >>> img = tree.css_first('img')
625
+ >>> img.replace_with(img.attributes.get('alt', ''))
626
+ >>> tree.body.child.html
627
+ '<div>Get Laptop</div>'
628
+
629
+ >>> html_parser = HTMLParser('<div>Get <span alt="Laptop"><img src="/jpg"> <div></div></span></div>')
630
+ >>> html_parser2 = HTMLParser('<div>Test</div>')
631
+ >>> img_node = html_parser.css_first('img')
632
+ >>> img_node.replace_with(html_parser2.body.child)
633
+ '<div>Get <span alt="Laptop"><div>Test</div> <div></div></span></div>'
634
+ """
635
+ cdef myhtml_tree_node_t *node
636
+ if isinstance(value, (str, bytes, unicode)):
637
+ bytes_val = to_bytes(value)
638
+ node = myhtml_node_create(self.parser.html_tree, MyHTML_TAG__TEXT, MyHTML_NAMESPACE_HTML)
639
+ myhtml_node_text_set(node, <char*> bytes_val, len(bytes_val), MyENCODING_UTF_8)
640
+ myhtml_node_insert_before(self.node, node)
641
+ myhtml_node_delete(self.node)
642
+ elif isinstance(value, Node):
643
+ node = myhtml_node_clone_deep(self.parser.html_tree, <myhtml_tree_node_t *> value.node)
644
+ myhtml_node_insert_before(self.node, node)
645
+ myhtml_node_delete(self.node)
646
+ else:
647
+ raise TypeError("Expected a string or Node instance, but %s found" % type(value).__name__)
648
+
649
+ def insert_before(self, str_or_Node value):
650
+ """
651
+ Insert a node before the current Node.
652
+
653
+ Parameters
654
+ ----------
655
+ value : str, bytes or Node
656
+ The text or Node instance to insert before the Node.
657
+ When a text string is passed, it's treated as text. All HTML tags will be escaped.
658
+ Convert and pass the ``Node`` object when you want to work with HTML.
659
+ Does not clone the ``Node`` object.
660
+ All future changes to the passed ``Node`` object will also be taken into account.
661
+
662
+ Examples
663
+ --------
664
+
665
+ >>> tree = HTMLParser('<div>Get <img src="" alt="Laptop"></div>')
666
+ >>> img = tree.css_first('img')
667
+ >>> img.insert_before(img.attributes.get('alt', ''))
668
+ >>> tree.body.child.html
669
+ '<div>Get Laptop<img src="" alt="Laptop"></div>'
670
+
671
+ >>> html_parser = HTMLParser('<div>Get <span alt="Laptop"><img src="/jpg"> <div></div></span></div>')
672
+ >>> html_parser2 = HTMLParser('<div>Test</div>')
673
+ >>> img_node = html_parser.css_first('img')
674
+ >>> img_node.insert_before(html_parser2.body.child)
675
+ <div>Get <span alt="Laptop"><div>Test</div><img src="/jpg"> <div></div></span></div>'
676
+ """
677
+ cdef myhtml_tree_node_t *node
678
+ if isinstance(value, (str, bytes, unicode)):
679
+ bytes_val = to_bytes(value)
680
+ node = myhtml_node_create(self.parser.html_tree, MyHTML_TAG__TEXT, MyHTML_NAMESPACE_HTML)
681
+ myhtml_node_text_set(node, <char*> bytes_val, len(bytes_val), MyENCODING_UTF_8)
682
+ myhtml_node_insert_before(self.node, node)
683
+ elif isinstance(value, Node):
684
+ node = myhtml_node_clone_deep(self.parser.html_tree, <myhtml_tree_node_t *> value.node)
685
+ myhtml_node_insert_before(self.node, node)
686
+ else:
687
+ raise TypeError("Expected a string or Node instance, but %s found" % type(value).__name__)
688
+
689
+ def insert_after(self, str_or_Node value):
690
+ """
691
+ Insert a node after the current Node.
692
+
693
+ Parameters
694
+ ----------
695
+ value : str, bytes or Node
696
+ The text or Node instance to insert after the Node.
697
+ When a text string is passed, it's treated as text. All HTML tags will be escaped.
698
+ Convert and pass the ``Node`` object when you want to work with HTML.
699
+ Does not clone the ``Node`` object.
700
+ All future changes to the passed ``Node`` object will also be taken into account.
701
+
702
+ Examples
703
+ --------
704
+
705
+ >>> tree = HTMLParser('<div>Get <img src="" alt="Laptop"></div>')
706
+ >>> img = tree.css_first('img')
707
+ >>> img.insert_after(img.attributes.get('alt', ''))
708
+ >>> tree.body.child.html
709
+ '<div>Get <img src="" alt="Laptop">Laptop</div>'
710
+
711
+ >>> html_parser = HTMLParser('<div>Get <span alt="Laptop"><img src="/jpg"> <div></div></span></div>')
712
+ >>> html_parser2 = HTMLParser('<div>Test</div>')
713
+ >>> img_node = html_parser.css_first('img')
714
+ >>> img_node.insert_after(html_parser2.body.child)
715
+ <div>Get <span alt="Laptop"><img src="/jpg"><div>Test</div> <div></div></span></div>'
716
+ """
717
+ cdef myhtml_tree_node_t *node
718
+ if isinstance(value, (str, bytes, unicode)):
719
+ bytes_val = to_bytes(value)
720
+ node = myhtml_node_create(self.parser.html_tree, MyHTML_TAG__TEXT, MyHTML_NAMESPACE_HTML)
721
+ myhtml_node_text_set(node, <char*> bytes_val, len(bytes_val), MyENCODING_UTF_8)
722
+ myhtml_node_insert_after(self.node, node)
723
+ elif isinstance(value, Node):
724
+ node = myhtml_node_clone_deep(self.parser.html_tree, <myhtml_tree_node_t *> value.node)
725
+ myhtml_node_insert_after(self.node, node)
726
+ else:
727
+ raise TypeError("Expected a string or Node instance, but %s found" % type(value).__name__)
728
+
729
+ def insert_child(self, str_or_Node value):
730
+ """
731
+ Insert a node inside (at the end of) the current Node.
732
+
733
+ Parameters
734
+ ----------
735
+ value : str, bytes or Node
736
+ The text or Node instance to insert inside the Node.
737
+ When a text string is passed, it's treated as text. All HTML tags will be escaped.
738
+ Convert and pass the ``Node`` object when you want to work with HTML.
739
+ Does not clone the ``Node`` object.
740
+ All future changes to the passed ``Node`` object will also be taken into account.
741
+
742
+ Examples
743
+ --------
744
+
745
+ >>> tree = HTMLParser('<div>Get <img src=""></div>')
746
+ >>> div = tree.css_first('div')
747
+ >>> div.insert_child('Laptop')
748
+ >>> tree.body.child.html
749
+ '<div>Get <img src="">Laptop</div>'
750
+
751
+ >>> html_parser = HTMLParser('<div>Get <span alt="Laptop"> <div>Laptop</div> </span></div>')
752
+ >>> html_parser2 = HTMLParser('<div>Test</div>')
753
+ >>> span_node = html_parser.css_first('span')
754
+ >>> span_node.insert_child(html_parser2.body.child)
755
+ <div>Get <span alt="Laptop"> <div>Laptop</div> <div>Test</div> </span></div>'
756
+ """
757
+ cdef myhtml_tree_node_t *node
758
+ if isinstance(value, (str, bytes, unicode)):
759
+ bytes_val = to_bytes(value)
760
+ node = myhtml_node_create(self.parser.html_tree, MyHTML_TAG__TEXT, MyHTML_NAMESPACE_HTML)
761
+ myhtml_node_text_set(node, <char*> bytes_val, len(bytes_val), MyENCODING_UTF_8)
762
+ myhtml_node_append_child(self.node, node)
763
+ elif isinstance(value, Node):
764
+ node = myhtml_node_clone_deep(self.parser.html_tree, <myhtml_tree_node_t *> value.node)
765
+ myhtml_node_append_child(self.node, node)
766
+ else:
767
+ raise TypeError("Expected a string or Node instance, but %s found" % type(value).__name__)
768
+
769
+ def unwrap_tags(self, list tags, delete_empty = False):
770
+ """Unwraps specified tags from the HTML tree.
771
+
772
+ Works the same as th ``unwrap`` method, but applied to a list of tags.
773
+
774
+ Parameters
775
+ ----------
776
+ tags : list
777
+ List of tags to remove.
778
+ delete_empty : bool, default False
779
+ Whenever to delete empty tags.
780
+
781
+ Examples
782
+ --------
783
+
784
+ >>> tree = HTMLParser("<div><a href="">Hello</a> <i>world</i>!</div>")
785
+ >>> tree.body.unwrap_tags(['i','a'])
786
+ >>> tree.body.html
787
+ '<body><div>Hello world!</div></body>'
788
+
789
+ Note: by default, empty tags are ignored, set "delete_empty" to "True" to change this.
790
+ """
791
+
792
+ for tag in tags:
793
+ for element in self.css(tag):
794
+ element.unwrap(delete_empty)
795
+
796
+ @property
797
+ def raw_value(self):
798
+ """Return the raw (unparsed, original) value of a node.
799
+
800
+ Currently, works on text nodes only.
801
+
802
+ Returns
803
+ -------
804
+
805
+ raw_value : bytes
806
+
807
+ Examples
808
+ --------
809
+
810
+ >>> html_parser = HTMLParser('<div>&#x3C;test&#x3E;</div>')
811
+ >>> selector = html_parser.css_first('div')
812
+ >>> selector.child.html
813
+ '&lt;test&gt;'
814
+ >>> selector.child.raw_value
815
+ b'&#x3C;test&#x3E;'
816
+ """
817
+ cdef int begin = self.node.token.element_begin
818
+ cdef int length = self.node.token.element_length
819
+ if self.node.tag_id != MyHTML_TAG__TEXT:
820
+ raise ValueError("Can't obtain raw value for non-text node.")
821
+ return self.parser.raw_html[begin:begin + length]
822
+
823
+ def select(self, query=None):
824
+ """Select nodes given a CSS selector.
825
+
826
+ Works similarly to the ``css`` method, but supports chained filtering and extra features.
827
+
828
+ Parameters
829
+ ----------
830
+ query : str or None
831
+ The CSS selector to use when searching for nodes.
832
+
833
+ Returns
834
+ -------
835
+ selector : The `Selector` class.
836
+ """
837
+ return Selector(self, query)
838
+
839
+ def scripts_contain(self, str query):
840
+ """Returns True if any of the script tags contain specified text.
841
+
842
+ Caches script tags on the first call to improve performance.
843
+
844
+ Parameters
845
+ ----------
846
+ query : str
847
+ The query to check.
848
+
849
+ """
850
+ if self.parser.cached_script_texts is None:
851
+ nodes = find_nodes(self.parser, self.node, 'script')
852
+ text_nodes = []
853
+ for node in nodes:
854
+ node_text = node.text(deep=True)
855
+ if node_text:
856
+ text_nodes.append(node_text)
857
+ self.parser.cached_script_texts = text_nodes
858
+
859
+ for text in self.parser.cached_script_texts:
860
+ if query in text:
861
+ return True
862
+ return False
863
+
864
+ def script_srcs_contain(self, tuple queries):
865
+ """Returns True if any of the script SRCs attributes contain on of the specified text.
866
+
867
+ Caches values on the first call to improve performance.
868
+
869
+ Parameters
870
+ ----------
871
+ queries : tuple of str
872
+
873
+ """
874
+ if self.parser.cached_script_srcs is None:
875
+ nodes = find_nodes(self.parser, self.node, 'script')
876
+ src_nodes = []
877
+ for node in nodes:
878
+ node_src = node.attrs.get('src')
879
+ if node_src:
880
+ src_nodes.append(node_src)
881
+ self.parser.cached_script_srcs = src_nodes
882
+
883
+ for text in self.parser.cached_script_srcs:
884
+ for query in queries:
885
+ if query in text:
886
+ return True
887
+ return False
888
+
889
+ def __repr__(self):
890
+ return '<Node %s>' % self.tag
891
+
892
+ def __eq__(self, other):
893
+ if isinstance(other, str):
894
+ return self.html == other
895
+ if not isinstance(other, Node):
896
+ return False
897
+ return self.html == other.html
898
+ @property
899
+ def text_content(self):
900
+ """Returns the text of the node if it is a text node.
901
+
902
+ Returns None for other nodes.
903
+ Unlike the ``text`` method, does not include child nodes.
904
+
905
+ Returns
906
+ -------
907
+ text : str or None.
908
+ """
909
+ text = ""
910
+ cdef const char* c_text
911
+ cdef myhtml_tree_node_t *node = self.node.child
912
+
913
+ if self.node.tag_id == MyHTML_TAG__TEXT:
914
+ c_text = myhtml_node_text(self.node, NULL)
915
+ if c_text != NULL:
916
+ node_text = c_text.decode(_ENCODING, self.parser.decode_errors)
917
+ return append_text(text, node_text)
918
+ return None
919
+
920
+ def merge_text_nodes(self):
921
+ """Iterates over all text nodes and merges all text nodes that are close to each other.
922
+
923
+ This is useful for text extraction.
924
+ Use it when you need to strip HTML tags and merge "dangling" text.
925
+
926
+ Examples
927
+ --------
928
+
929
+ >>> tree = HTMLParser("<div><p><strong>J</strong>ohn</p><p>Doe</p></div>")
930
+ >>> node = tree.css_first('div')
931
+ >>> tree.unwrap_tags(["strong"])
932
+ >>> tree.text(deep=True, separator=" ", strip=True)
933
+ "J ohn Doe" # Text extraction produces an extra space because the strong tag was removed.
934
+ >>> node.merge_text_nodes()
935
+ >>> tree.text(deep=True, separator=" ", strip=True)
936
+ "John Doe"
937
+ """
938
+ cdef Stack stack = Stack(_STACK_SIZE)
939
+ cdef myhtml_tree_node_t * current_node = NULL
940
+ cdef Node next_node
941
+ cdef const char* left_text
942
+ cdef const char* right_text
943
+ cdef char* final_text
944
+ cdef size_t left_length, right_length, final_length
945
+
946
+ stack.push(self.node)
947
+
948
+ while not stack.is_empty():
949
+ current_node = stack.pop()
950
+
951
+ if current_node.tag_id == MyHTML_TAG__TEXT and current_node.prev and \
952
+ current_node.prev.tag_id == MyHTML_TAG__TEXT:
953
+ left_text = myhtml_node_text(current_node.prev, &left_length)
954
+ right_text = myhtml_node_text(current_node, &right_length)
955
+ if left_text and right_text:
956
+ final_length = left_length + right_length
957
+ final_text = <char *>malloc(final_length + 1)
958
+ if final_text == NULL:
959
+ raise MemoryError("Can't allocate memory for a new node.")
960
+ memcpy(final_text, left_text, left_length)
961
+ memcpy(final_text + left_length, right_text, right_length + 1)
962
+ myhtml_node_text_set(current_node, <const char *>final_text, final_length, MyENCODING_UTF_8)
963
+ myhtml_node_delete(current_node.prev)
964
+ free(final_text)
965
+
966
+ if current_node.next is not NULL:
967
+ stack.push(current_node.next)
968
+
969
+ if current_node.child is not NULL:
970
+ stack.push(current_node.child)
971
+
972
+ cdef inline str append_text(str text, str node_text, str separator='', bint strip=False):
973
+ if strip:
974
+ text += node_text.strip() + separator
975
+ else:
976
+ text += node_text + separator
977
+
978
+ return text
979
+
980
+
981
+ cdef inline bytes to_bytes(str_or_Node value):
982
+ cdef bytes bytes_val
983
+ if isinstance(value, unicode):
984
+ bytes_val = <bytes>value.encode("utf-8")
985
+ elif isinstance(value, bytes):
986
+ bytes_val = <bytes>value
987
+ return bytes_val