Repository navigation
Expand file tree
/
Copy pathParser.py
More file actions
executable file
·1431 lines (1009 loc) · 50.7 KB
/
Copy pathParser.py
File metadata and controls
executable file
·1431 lines (1009 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Copyright (c) 2015, 2016, 2017, 2018, 2019 Tim Savannah under LGPLv3. All Rights Reserved.
See LICENSE (https://gnu.org/licenses/lgpl-3.0.txt) for more information.
Parser Implementation
'''
# In general below, all "tag names" (body, div, etc) should be lowercase. The parser will lowercase internally. All attribute names (like `id` in id="123") provided to search functions should be lowercase. Values are not lowercase. This is because doing tons of searches, lowercasing every search can quickly build up. Lowercase it once in your code, not every time you call a function.
import re
#import sys
import uuid
# Python 2/3 compatibility:
try:
from HTMLParser import HTMLParser
pyver = 2
except ImportError:
from html.parser import HTMLParser
pyver = 3
try:
file
except NameError:
from io import TextIOWrapper as file
from collections import defaultdict
from .constants import IMPLICIT_SELF_CLOSING_TAGS, INVISIBLE_ROOT_TAG, INVISIBLE_ROOT_TAG_START, INVISIBLE_ROOT_TAG_END
from .exceptions import MultipleRootNodeException
from .Tags import AdvancedTag, TagCollection, canFilterTags, FilterableTagCollection
import codecs
from .utils import stripIEConditionals, addStartTag
__all__ = ('AdvancedHTMLParser', 'IndexedAdvancedHTMLParser')
def isInvisibleRootTag(tag):
'''
isInvisibleRootTag - Check if #tag is a the special root tag when there are multiple root elements.
@param tag <AdvancedTag> - A tag
@return <bool> - True if tag is the "fake" root tag used when multiple elements are at root level, otherwise False.
'''
return bool(tag.tagName == INVISIBLE_ROOT_TAG)
class AdvancedHTMLParser(HTMLParser):
'''
AdvancedHTMLParser - This class parses and allows searching of documents
'''
def __init__(self, filename=None, encoding='utf-8'):
'''
__init__ - Creates an Advanced HTML parser object. For read-only parsing, consider IndexedAdvancedHTMLParser for faster searching.
@param filename <str> - Optional filename to parse. Otherwise use parseFile or parseStr methods.
@param encoding <str> - Specifies the document encoding. Default utf-8
'''
HTMLParser.__init__(self)
# Do not automatically convert charrefs in python3
self.convert_charrefs = False
# Encoding to use for this document
self.encoding = encoding
self._inTag = []
self.root = None
self.doctype = None
self.reset = self._reset # Must assign after first call, otherwise members won't yet be present
if filename is not None:
self.parseFile(filename)
###########################################
##### INTERNAL #######
###########################################
def __getstate__(self):
'''
__getstate__ - Get state for pickling
@return <dict>
'''
state = self.__dict__
# Python2 compat
del state['reset']
return state
def __setstate__(self, state):
'''
__setstate - Restore state for loading pickle
@param state <dict> - The state
'''
for key, value in state.items():
setattr(self, key, value)
# Python2 compat
self.reset = self._reset
def _hasTagInParentLine(self, tag, root):
if tag == root or tag.parentNode == root:
return True
if tag.parentNode is None:
return False
return self._hasTagInParentLine(tag.parentNode, root)
def _handleRootArg(self, root):
# Check if tag is string of root and apply to real root.
# If real root is unparsed: raise an error.
# Otherwise: return passed arg.
# Return is tuple (root, isRoot)
if root == 'root' or root == self.root:
return (self.root, True)
return (root, False)
######## Parsing #########
def handle_starttag(self, tagName, attributeList, isSelfClosing=False):
'''
Internal for parsing
'''
tagName = tagName.lower()
inTag = self._inTag
if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS:
isSelfClosing = True
newTag = AdvancedTag(tagName, attributeList, isSelfClosing, ownerDocument=self)
if self.root is None:
self.root = newTag
elif len(inTag) > 0:
inTag[-1].appendChild(newTag)
else:
raise MultipleRootNodeException()
if isSelfClosing is False:
inTag.append(newTag)
return newTag
def handle_startendtag(self, tagName, attributeList):
'''
Internal for parsing
'''
return self.handle_starttag(tagName, attributeList, True)
def handle_endtag(self, tagName):
'''
Internal for parsing
'''
try:
foundIt = False
inTag = self._inTag
for i in range(len(inTag)):
if inTag[i].tagName == tagName:
foundIt = True
break
if not foundIt:
return
# Handle closing tags which should have been closed but weren't
while inTag[-1].tagName != tagName:
inTag.pop()
inTag.pop()
except:
pass
def handle_data(self, data):
'''
Internal for parsing
'''
if data:
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText(data)
elif data.strip(): #and not self.getRoot():
# Must be text prior to or after root node
raise MultipleRootNodeException()
def handle_entityref(self, entity):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('&%s;' %(entity,))
else:
raise MultipleRootNodeException()
def handle_charref(self, charRef):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('&#%s;' %(charRef,))
else:
raise MultipleRootNodeException()
def handle_comment(self, comment):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('<!-- %s -->' %(comment,))
else:
raise MultipleRootNodeException()
def handle_decl(self, decl):
'''
Internal for parsing
'''
self.doctype = decl
def unknown_decl(self, decl):
'''
Internal for parsing
'''
if not self.doctype:
self.doctype = decl
###########################################
##### Public #######
###########################################
def getRoot(self):
'''
getRoot - returns the root Tag.
NOTE: if there are multiple roots, this will be a special tag.
You may want to consider using getRootNodes instead if this
is a possible situation for you.
@return AdvancedTag
'''
return self.root
def getRootNodes(self):
'''
getRootNodes - Gets all objects at the "root" (first level; no parent). Use this if you may have multiple roots (not children of <html>)
Use this method to get objects, for example, in an AJAX request where <html> may not be your root.
Note: If there are multiple root nodes (i.e. no <html> at the top), getRoot will return a special tag. This function automatically
handles that, and returns all root nodes.
@return list<AdvancedTag> - A list of AdvancedTags which are at the root level of the tree.
'''
root = self.root
if not root:
return []
if root.tagName == INVISIBLE_ROOT_TAG:
return list(root.children)
return [root]
def getAllNodes(self):
'''
getAllNodes - Get every element
@return TagCollection<AdvancedTag>
'''
ret = TagCollection()
for rootNode in self.getRootNodes():
ret.append(rootNode)
ret += rootNode.getAllChildNodes()
return ret
def setRoot(self, root):
'''
Sets the root node, and reprocesses the indexes
'''
self.root = root
def setDoctype(self, newDoctype):
'''
setDoctype - Set the doctype for this document, or clear it.
@param newDoctype <str/None> -
If None, will clear the doctype and not return one with #getHTML
Otherwise, a string of the full doctype tag.
For example, the HTML5 doctype would be "DOCTYPE html"
'''
self.doctype = newDoctype
def getElementsByTagName(self, tagName, root='root'):
'''
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and root.tagName == tagName:
elements.append(root)
getElementsByTagName = self.getElementsByTagName
for child in root.children:
if child.tagName == tagName:
elements.append(child)
elements += getElementsByTagName(tagName, child)
return TagCollection(elements)
def getElementsByName(self, name, root='root'):
'''
getElementsByName - Searches and returns all elements with a specific name.
@param name <str> - A string of the name attribute
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root' [default], the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and root.name == name:
elements.append(root)
getElementsByName = self.getElementsByName
for child in root.children:
if child.getAttribute('name') == name:
elements.append(child)
elements += getElementsByName(name, child)
return TagCollection(elements)
def getElementById(self, _id, root='root'):
'''
getElementById - Searches and returns the first (should only be one) element with the given ID.
@param id <str> - A string of the id attribute.
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root' [default], the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
if isFromRoot is True and root.id == _id:
return root
getElementById = self.getElementById
for child in root.children:
if child.getAttribute('id') == _id:
return child
potential = getElementById(_id, child)
if potential is not None:
return potential
return None
def getElementsByClassName(self, className, root='root'):
'''
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - One or more space-separated class names
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root' [default], the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
# Generate list of all classnames to match
classNames = [x.strip() for x in className.strip().split(' ') if x.strip()]
# Run through entire tree on the first
className = classNames.pop(0)
if isFromRoot is True and className in root.classNames:
elements.append(root)
getElementsByClassName = self.getElementsByClassName
for child in root.children:
if className in child.classNames:
elements.append(child)
elements += getElementsByClassName(className, child)
# Check if we need to match against any other names
if len(classNames) > 0:
elements = [ em for em in elements for matchClassName in classNames if matchClassName in em.classList ]
return TagCollection(elements)
def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute name
@param attrValue <str> - Expected value of attribute
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and root.getAttribute(attrName) == attrValue:
elements.append(root)
getElementsByAttr = self.getElementsByAttr
for child in root.children:
if child.getAttribute(attrName) == attrValue:
elements.append(child)
elements += getElementsByAttr(attrName, attrValue, child)
return TagCollection(elements)
def getElementsWithAttrValues(self, attrName, attrValues, root='root'):
'''
getElementsWithAttrValues - Returns elements with an attribute, named by #attrName contains one of the values in the list, #values
@param attrName <lowercase str> - A lowercase attribute name
@param attrValues set<str> - A set of all valid values.
@return - TagCollection of all matching elements
'''
(root, isFromRoot) = self._handleRootArg(root)
if type(attrValues) != set:
attrValues = set(attrValues)
return root.getElementsWithAttrValues(attrName, attrValues)
def getElementsCustomFilter(self, filterFunc, root='root'):
'''
getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@return - TagCollection of all matching elements
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and filterFunc(root) is True:
elements.append(root)
getElementsCustomFilter = self.getElementsCustomFilter
for child in root.children:
if filterFunc(child) is True:
elements.append(child)
elements += getElementsCustomFilter(filterFunc, child)
return TagCollection(elements)
def getElementsByXPathExpression(self, xpathExprStr):
'''
getElementsByXPathExpression - Evaluate an XPath expression string against this document
@param xpathExprStr <str> - An XPath expression string (e.x. """//div[@name="someName"]/span[3]""" )
@return <TagCollection> - TagCollection of all matching elements
@see AdvancedHTMLParser.xpath.XPathExpression.evaluate for @throws and similar
'''
rootNodes = self.getRootNodes()
# Late-binding import
from . import xpath as axpath
# May raise a parsing error, if invalid xpath expression string
xpathExpression = axpath.XPathExpression(xpathExprStr)
# TODO: From multiple root nodes??
return xpathExpression.evaluate(rootNodes)
getElementsByXPath = getElementsByXPathExpression
def getFirstElementCustomFilter(self, filterFunc, root='root'):
'''
getFirstElementCustomFilter - Scan elements using a provided function, stop and return the first match.
@see getElementsCustomFilter to match multiple elements
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@return - An AdvancedTag of the node that matched, or None if no match.
'''
(root, isFromRoot) = self._handleRootArg(root)
#elements = []
if isFromRoot is True and filterFunc(root) is True:
return root
getFirstElementCustomFilter = self.getFirstElementCustomFilter
for child in root.children:
if filterFunc(child) is True:
return child
subRet = getFirstElementCustomFilter(filterFunc, child)
if subRet:
return subRet
return None
def evaluate(self, xpathExprStr, whichDoc=None):
'''
evaluate - Evaluate an xpath expression against this document
@param xpathExprStr <str> - An XPath expression string (e.x. """//div[@name="someName"]/span[3]""" )
@param whichDoc <None/Parser.AdvancedHTMLParser> Default None - Which document.
NOTE: This is for compatibility with the JS DOM interface.
This must be None (Default) to refer to the current document, or "self" to refer to the same.
May allow other values in the future.
@return <TagCollection> - TagCollection of all matching elements
NOTE: JS DOM returns an iterable object for this function's return. May in the future match that interface.
For now the XPath engine does not run off a generator, so this will likely at first be a wrapper for interface compatibility sake
@see AdvancedHTMLParser.xpath.XPathExpression.evaluate for @throws and similar
'''
# Just validate for interface sake right now
if whichDoc is not None and whichDoc is not self:
raise ValueError('Parser.AdvancedHTMLParser.evaluate must be called with None/default as second argument, or self.')
# Break from interface and just return the straight tag collection
return self.getElementsByXPathExpression(xpathExprStr)
@property
def body(self):
'''
body - Get the body element
@return <AdvancedTag> - The body tag, or None if no body tag present
'''
return self.getFirstElementCustomFilter(lambda em : em.tagName == 'body')
@property
def head(self):
'''
head - Get the head element
@return <AdvancedTag> - The head tag, or None if no head tag present
'''
return self.getFirstElementCustomFilter(lambda em : em.tagName == 'head')
@property
def forms(self):
'''
forms - Return all forms associated with this document
@return <TagCollection> - All "form" elements
'''
return self.getElementsByTagName('form')
def contains(self, em):
'''
Checks if #em is found anywhere within this element tree
@param em <AdvancedTag> - Tag of interest
@return <bool> - If element #em is within this tree
'''
for rootNode in self.getRootNodes():
if rootNode.contains(em):
return True
return False
__contains__ = contains
def containsUid(self, uid):
'''
Check if #uid is found anywhere within this element tree
@param uid <uuid.UUID> - Uid
@return <bool> - If #uid is found within this tree
'''
for rootNode in self.getRootNodes():
if rootNode.containsUid(uid):
return True
return False
def __contains__(self, other):
if isinstance(other, uuid.UUID):
return self.containsUid(other)
elif issubclass(other.__class__, AdvancedTag):
return self.contains(other)
else:
raise TypeError('Invalid operand, should be either a uuid.UUID object or an AdvancedTag')
def filter(self, **kwargs):
'''
filter aka filterAnd - Filter ALL the elements in this DOM.
Results must match ALL the filter criteria. for ANY, use the *Or methods
Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed
without '--no-deps' flag.)
For alternative without QueryableList,
consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods
Special Keys:
tagname - The tag name
text - The inner text
@return TagCollection<AdvancedTag>
'''
if canFilterTags is False:
raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.')
allNodes = self.getAllNodes()
filterableNodes = FilterableTagCollection(allNodes)
return filterableNodes.filterAnd(**kwargs)
filterAnd = filter
def filterOr(self, **kwargs):
'''
filterOr - Perform a filter operation on this node and all children (and their children, onto the end)
Results must match ANY the filter criteria. for ALL, use the *AND methods
For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter
Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed
without '--no-deps' flag.)
For alternative, consider AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods
@return TagCollection<AdvancedTag>
'''
if canFilterTags is False:
raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.')
allNodes = self.getAllNodes() + [self]
filterableNodes = FilterableTagCollection(allNodes)
return filterableNodes.filterOr(**kwargs)
def find(self, **kwargs):
'''
find - Perform a search of elements using attributes as keys and potential values as values
(i.e. parser.find(name='blah', tagname='span') will return all elements in this document
with the name "blah" of the tag type "span" )
Arguments are key = value, or key can equal a tuple/list of values to match ANY of those values.
Append a key with __contains to test if some strs (or several possible strs) are within an element
Append a key with __icontains to perform the same __contains op, but ignoring case
Special keys:
tagname - The tag name of the element
text - The text within an element
NOTE: Empty string means both "not set" and "no value" in this implementation.
NOTE: If you installed the QueryableList module (i.e. ran setup.py without --no-deps) it is
better to use the "filter"/"filterAnd" or "filterOr" methods, which are also available
on all tags and tag collections (tag collections also have filterAllAnd and filterAllOr)
@return TagCollection<AdvancedTag> - A list of tags that matched the filter criteria
'''
if not kwargs:
return TagCollection()
# Because of how closures work in python, need a function to generate these lambdas
# because the closure basically references "current key in iteration" and not
# "actual instance" of variable. Seems to me to be a bug... but whatever
def _makeTagnameLambda(tagName):
return lambda em : em.tagName == tagName
def _makeAttributeLambda(_key, _value):
return lambda em : em.getAttribute(_key, '') == _value
def _makeTagnameInLambda(tagNames):
return lambda em : em.tagName in tagNames
def _makeAttributeInLambda(_key, _values):
return lambda em : em.getAttribute(_key, '') in _values
def _makeTextLambda(_value):
return lambda em : em.text == _value
def _makeTextInLambda(_values):
return lambda em : em.text in _values
def _makeAttributeContainsLambda(_key, _value, icontains=False):
if icontains is False:
return lambda em : _value in em.getAttribute(_key, '')
else:
_value = _value.lower()
return lambda em : _value in em.getAttribute(_key, '').lower()
def _makeTextContainsLambda(_value, icontains=False):
if icontains is False:
return lambda em : _value in em.text
else:
_value = _value.lower()
return lambda em : _value in em.text.lower()
def _makeAttributeContainsInLambda(_key, _values, icontains=False):
if icontains:
_values = tuple([x.lower() for x in _values])
def _testFunc(em):
attrValue = em.getAttribute(_key, '')
if icontains:
attrValue = attrValue.lower()
for value in _values:
if value in attrValue:
return True
return False
return _testFunc
def _makeTextContainsInLambda(_values, icontains=False):
if icontains:
_values = tuple([x.lower() for x in _values])
def _testFunc(em):
text = em.text
if icontains:
text = text.lower()
for value in _values:
if value in text:
return True
return False
return _testFunc
# This will hold all the functions we will chain for matching
matchFunctions = []
# Iterate over all the filter portions, and build a filter.
for key, value in kwargs.items():
key = key.lower()
endsIContains = key.endswith('__icontains')
endsContains = key.endswith('__contains')
isValueList = isinstance(value, (list, tuple))
thisFunc = None
if endsIContains or endsContains:
key = re.sub('__[i]{0,1}contains$', '', key)
if key == 'tagname':
raise ValueError('tagname is not supported for contains')
if isValueList:
if key == 'text':
thisFunc = _makeTextContainsInLambda(value, icontains=endsIContains)
else:
thisFunc = _makeAttributeContainsLambda(key, value, icontains=endsIContains)
else:
if key == 'text':
thisFunc = _makeTextContainsLambda(value, icontains=endsIContains)
else:
thisFunc = _makeAttributeContainsLambda(key, value, icontains=endsIContains)
else:
# Not contains, straight up
if isValueList:
if key == 'tagname':
thisFunc = _makeTagnameInLambda(value)
elif key == 'text':
thisFunc = _makeTextInLambda(value)
else:
thisFunc = _makeAttributeInLambda(key, value)
else:
if key == 'tagname':
thisFunc = _makeTagnameLambda(value)
elif key == 'text':
thisFunc = _makeTextLambda(value)
else:
thisFunc = _makeAttributeLambda(key, value)
matchFunctions.append( thisFunc )
# The actual matching function - This will run through the assembled
# #matchFunctions list, testing the element against each match
# and returning all elements in a TagCollection that match this list.
def doMatchFunc(em):
for matchFunction in matchFunctions:
if matchFunction(em) is False:
return False
return True
return self.getElementsCustomFilter(doMatchFunc)
def getHTML(self):
'''
getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML
'''
root = self.getRoot()
if root is None:
raise ValueError('Did not parse anything. Use parseFile or parseStr')
if self.doctype:
doctypeStr = '<!%s>\n' %(self.doctype)
else:
doctypeStr = ''
# 6.6.0: If we have a real root tag, print the outerHTML. If we have a fake root tag (for multiple root condition),
# then print the innerHTML (skipping the outer root tag). Otherwise, we will miss
# untagged text (between the multiple root nodes).
rootNode = self.getRoot()
if rootNode.tagName == INVISIBLE_ROOT_TAG:
return doctypeStr + rootNode.innerHTML
else:
return doctypeStr + rootNode.outerHTML
# return doctypeStr + ''.join([elem.outerHTML for elem in self.getRootNodes()])
# toHTML - Alias of getHTML
toHTML = getHTML
# asHTML - Alias of getHTML
asHTML = getHTML
def getFormattedHTML(self, indent=' '):
'''
getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace
with a pretty-printed version
@param indent - space/tab/newline of each level of indent, or integer for how many spaces per level
@return - <str> Formatted html
@see getHTML - Get HTML with original whitespace
@see getMiniHTML - Get HTML with only functional whitespace remaining
'''
from .Formatter import AdvancedHTMLFormatter
html = self.getHTML()
formatter = AdvancedHTMLFormatter(indent, None) # Do not double-encode
formatter.feed(html)
return formatter.getHTML()
def getMiniHTML(self):
'''
getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present
'''
from .Formatter import AdvancedHTMLMiniFormatter
html = self.getHTML()
formatter = AdvancedHTMLMiniFormatter(None) # Do not double-encode
formatter.feed(html)
return formatter.getHTML()
def _reset(self):
'''
_reset - reset this object. Assigned to .reset after __init__ call.
'''
HTMLParser.reset(self)
self.root = None
self.doctype = None
self._inTag = []
def feed(self, contents):
'''
feed - Feed contents. Use parseStr or parseFile instead.
@param contents - Contents
'''
contents = stripIEConditionals(contents)
try:
HTMLParser.feed(self, contents)
except MultipleRootNodeException:
self.reset()
HTMLParser.feed(self, "%s%s" %(addStartTag(contents, INVISIBLE_ROOT_TAG_START), INVISIBLE_ROOT_TAG_END))
def parseFile(self, filename):
'''
parseFile - Parses a file and creates the DOM tree and indexes
@param filename <str/file> - A string to a filename or a file object. If file object, it will not be closed, you must close.
'''
self.reset()
if isinstance(filename, file):
contents = filename.read()
else:
with codecs.open(filename, 'r', encoding=self.encoding) as f:
contents = f.read()
self.feed(contents)
def parseStr(self, html):
'''
parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML
'''
self.reset()
if isinstance(html, bytes):
self.feed(html.decode(self.encoding))
else:
self.feed(html)
def createElement(self, tagName):
'''
createElement - Create an unattached tag with the given tag name
@param tagName <str> - Name of tag
@return <AdvancedTag> - A tag with the given tag name
'''
return AdvancedTag(tagName=tagName.lower())
@classmethod
def createElementFromHTML(cls, html, encoding='utf-8'):
'''
createElementFromHTML - Creates an element from a string of HTML.
If this could create multiple root-level elements (children are okay),
you must use #createElementsFromHTML which returns a list of elements created.