forked from bhimsen92/htmldom
/
htmldom.py
1419 lines (1300 loc) · 59.1 KB
/
htmldom.py
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
"""
HTMLDOM Library provides a simple interface for accessing and manipulating HTML documents.
You may find this library useful for building applications like screen-scraping.
Inspired by Jquery Library.
"""
import re
import os
from lexer import Lexer
elementName = r'<([\w\d_:]+)'
restName = r'(?:\s+)?((?:[\w\d_:-]+\s*\=\s*[\'"](?:[^"\']+)?[\'"]?\s*;?)*)?\s*(?:/)?>'
#StartTag
startTag = re.compile( elementName + restName )
#endTag
endTag = re.compile(r'\s*</\s*([\w\d_:]+)\s*>')
whiteSpace = re.compile(r'\s+')
#Used to spilt attributes into name/value pair i.e. ( class="one" ==> { 'class':'one' } )
attributeSplitter = re.compile(r'(?:([\w_\d:-]+)\s*\=\s*[\'"]([^"\']+)[\'"]\s*)')
#These regex are used for class and id based selection.
"""
i.e. given p.class#id
@regVar:selector matches the "p" element and @regVar:left will contain ".class"
and @regVar:right will hold the "#id" part.
"""
selector = re.compile(r'([\w_:\d*-]+)?((?:[#.\[][%?&+\s\w_ /:.\d#(),;\]\'"=$^*~\\-]+)*)?')
sep = r'(?:(?:[.#](?:[\w\d_:./-]+))'
leftSelector = r'|(?:\[\s*[\w\d_:*-]+\s*(?:[$*^~]?\s*\=\s*(?:[\'"]\s*[^"\']+\s*[\'"])|(?:[^\]]+))?\s*\]))?'
left = '('+sep + leftSelector+')'
right = r'((?:[*%#.\[][^"\']+)*)?'
newSelector = re.compile('(?:'+left + right+')?')
#This regex is used to detect [href*=someVal] | [href^=some_val] | [href$='someVal']
attributeSubStringSelector = re.compile(r'([~*$^])\s*\=')
emptyElements = [ "br", "hr", "meta", "link",
"base", "link", "img", "embed",
"param", "area", "col", "input",
"basefont", "frame", "isindex" ]
class HtmlDomNode:
def __init__( self, nodeName="text",nodeType=3):
self.nodeName = nodeName
self.nodeType = nodeType
self.parentNode = None
self.nextSiblingNode = None
self.previousSiblingNode = None
self.children = []
self.attributes = {}
self.ancestorList = []
self.text = ""
self.pos = -1
def setParentNode( self, parentNode ):
self.parentNode = parentNode
return self
def setSiblingNode( self, siblingNode ):
self.nextSiblingNode = siblingNode
return self
def setPreviousSiblingNode( self, siblingNode ):
self.previousSiblingNode = siblingNode
return self
def setChild( self, child ):
self.children.append( child )
return self
def setAttributes( self, attributeDict ):
self.attributes.update( attributeDict )
return self
def setAncestor( self, nodeList ):
self.ancestorList = list(nodeList)
return self
def setText( self, text ):
self.text = text
return self
def setAsFirstChild(self,node ):
self.children.insert( 0, node )
return self
def setAncestorsForChildren( self, ancestor ):
for childNode in self.children:
if not childNode.ancestorList:
childNode.generateAncestorList()
childNode.setAncestor( childNode.ancestorList + ancestor )
childNode.setAncestorsForChildren( ancestor )
return self
def firstChild(self):
return self.children[0]
def lastChild(self):
return self.children[-1]
def getNextSiblingNode( self ):
return self.nextSiblingNode
def getPreviousSiblingNode(self):
return self.previousSiblingNode
def getAncestorList(self):
return self.ancestorList
def getName(self):
return self.nodeName
def html(self, spaces = 0 ):
htmlStr = " " * spaces
htmlStr += "<" + self.nodeName
for attrName in self.attributes:
htmlStr += " " + attrName +"="+'"'+" ".join(self.attributes[attrName]) + '"'
htmlStr += '>'
for node in self.children:
if node.nodeType == 3:
htmlStr += "\n" + " " * ( spaces + 4 ) + node.text.strip()
else:
htmlStr += "\n" + node.html( spaces + 4 )
htmlStr += "\n" + " " * spaces + '</'+self.nodeName +'>'
return htmlStr
def getText(self):
textStr = ""
for node in self.children:
if node.nodeType == 3:
textStr += node.text
else:
textStr += node.getText() + '\n'
return textStr
def getNextSiblings(self):
siblingsSet = []
node = self.nextSiblingNode
while node:
if node not in siblingsSet and node.nodeType != 3 :
siblingsSet.append(node)
node = node.nextSiblingNode
return siblingsSet
def getPreviousSiblings(self):
siblingsSet = []
node = self.previousSiblingNode
while node:
if node not in siblingsSet and node.nodeType != 3:
siblingsSet.append(node)
node = node.previousSiblingNode
return siblingsSet
def attr( self, attrName, val = False ):
if val:
self.attributes[ attrName ] = val.split()
#return self.attributes.get( attrName, "Undefined Attribute" );
else:
return " ".join( self.attributes.get( attrName, ["Undefined","Attribute"] ) )
def removeAttr( self, attrName ):
if attrName in self.attributes.keys():
del self.attributes[ attrName ]
def remove( self, node ):
"""
This function must be called on parent node of the node.
It removes the node from the parents child list and adjusts
the sibling links.
"""
parent_node = self
if parent_node:
try:
pos = parent_node.children.index( node )
del parent_node.children[ pos ]
if node.previousSiblingNode and node.nextSiblingNode:
node.previousSiblingNode.nextSiblingNode = node.nextSiblingNode
node.nextSiblingNode.previousSiblingNode = node.previousSiblingNode
except ValueError:
raise Exception( str( node ) + ": node is not a children of the parent node" )
return node
def append( self, node ):
if isinstance( node, HtmlDomNode ):
if len( self.children ) == 0:
self.setChild( node )
else:
self.after( None, node )
node.setParentNode( self )
else:
raise Exception( "Invalid node object. object must be of type HtmlDomNode." )
def prepend( self, node ):
if isinstance( node, HtmlDomNode ):
if len( self.children ) == 0:
self.setAsFirstChild( node )
else:
self.before( None, node )
node.setParentNode( self )
else:
raise Exception( "Invalid node object. object must be of type Element." )
def after( self, src, target ):
"""
Function must be called on the parent node.
This function sets target node after the src node.
if src node is None then the target node will be set
as the last child of the parent node.
"""
flag = False
currNextSiblingNode = None
if src == None:
src = self.lastChild()
currNextSiblingNode = src.getNextSiblingNode()
self.setChild( target )
flag = True
if isinstance( target, HtmlDomNode ) and isinstance( src, HtmlDomNode ):
if not flag:
currNextSiblingNode = src.getNextSiblingNode()
index = self.children.index( src )
self.children.insert( index + 1, target )
target.setParentNode( self )
src.setSiblingNode( target )
target.setPreviousSiblingNode( src )
target.setSiblingNode( currNextSiblingNode )
if currNextSiblingNode:
currNextSiblingNode.setPreviousSiblingNode( target )
else:
raise Exception( "Invalid node object. object must be of type Element." )
def before( self, src, target ):
"""
Function must be called on the parent node.
This function sets target node before the src node.
if src node is None then the target node will be set
as the first child of the parent node.
"""
flag = False
currPrevSiblingNode = None
if src == None:
src = self.firstChild()
currPrevSiblingNode = src.getPreviousSiblingNode()
self.setAsFirstChild( target )
flag = True
if isinstance( target, HtmlDomNode ) and isinstance( src, HtmlDomNode ):
if not flag:
currPrevSiblingNode = src.getPreviousSiblingNode()
try:
index = self.children.index( src )
self.children.insert( index, target )
target.setParentNode( self )
except ValueError:
raise Exception( "source node object must be children of the parent object" )
src.setPreviousSiblingNode( target )
target.setSiblingNode( src )
target.setPreviousSiblingNode( currPrevSiblingNode )
if currPrevSiblingNode :
currPrevSiblingNode.setSiblingNode( target )
else:
raise Exception( "Invalid node object. object must be of type HtmlDomNode." )
def insertAfter( self, node ):
"""
This Function is similar to after but here
self is target node and "node" is the source node
"""
if isinstance( self, HtmlDomNode ) and isinstance( node, HtmlDomNode ):
node.parentNode.after( node, self )
def insertBefore( self, node ):
"""
This Function is similar to before but here
self is target node and node is the source node
"""
if isinstance( self, HtmlDomNode ) and isinstance( node, HtmlDomNode ):
node.parentNode.before( node, self )
def copy( self ):
"""
This function creats copy of the "self" node
"""
n = None
if self.nodeType == 1:
n = HtmlDomNode( self.nodeName, self.nodeType )
n.children = self.children
n.attributes = self.attributes
elif self.nodeType == 3:
n = HtmlDomNode()
n.text = self.text
return n
def generateAncestorList( self ):
parent = self.parentNode
while parent:
self.ancestorList.append( parent )
parent = parent.parentNode
class HtmlDom:
def __init__( self, url="" ):
self.baseURL = url
#@var:domNodes is a dictionary which holds all the tags present in the page.
# So that it will be very easy to look up the tags when queried.
self.domNodes = {}
self.domNodesList = []
self.referenceToRootElement = None
self.sorted = False
self.xml_file = False
def createDom(self,htmlString=None):
if htmlString:
data = htmlString
self.parseHTML( data )
#self.domDictToList()
else:
try:
try:
import urllib.request as urllib2
except ImportError:
#For python3
raise Exception( "urllib module not found" )
request = urllib2.Request(self.baseURL)
request.add_header('User-agent','Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en; rv:2.0) Gecko/25250101 Netscape/5.432b1 (C-MindSpring)')
response = urllib2.urlopen(request)
data = response.read().decode( self.getEncoding( response ) )
name, extension = os.path.splitext( self.baseURL )
if extension.lower().strip() == ".xml":
self.xml_file = True
self.parseHTML( data )
#self.domDictToList()
except Exception as e:
print("Error while reading url: %s" % (self.baseURL))
#new_addition:@start
raise Exception
#new_addition:@end
return self
def parseHTML( self, data ):
# pos is used in order to preserve their logical order of nodes in the document
# because i am using dictionary datastructure to store the nodes so while retriving
# nodes their orders will be different. In order to avoid that i sort the set on
# "pos" variable[ sort_function:time sort ]
pos = 1
index = 0
doc_seen = False
comment_string = "<!--"
#Node stack will hold the parent Nodes. The top most node will be the current parent.
nodeStack = []
lexer = Lexer( data )
while True:
data,loop = lexer.getToken()
data = data.strip()
if not loop:
break
if not data:
continue
#Doctype tag
if not doc_seen and ( data.find("<!DOCTYPE") == 0 or data.find("<!doctype") == 0 or data.find( "<?xml" ) == 0 ):
#Just pass through the doctype tag.
index = data.find(">")
data = data[ index + 1:]
doc_seen = True
continue
#Comment Node
for i in range( 0, 4 ):
if data[ i ] != comment_string[ i ]:
break
else:
#Just pass through the comment node.
index = data.find("-->")
data = data[index + 3:]
continue
#index is just used for extracting texts within the tags.
#could change in future.
index = data.find("<")
# len(nodeStack) >= 1 means found text content between the end of a tag and the start of a new tag
if len( nodeStack ) >= 1:
_index = -1
#if "script" element is on the top of the stack then entire content of it will be stored in a single text node
if nodeStack[-1].getName() == "script":
_index = data.find( "</script>" )
if _index != -1:
tmpData = data[ :_index ]
#if "style" element is on the top of the stack then entire content of it will be stored in a single text node
elif nodeStack[-1].getName() == "style":
_index = data.find("</style>")
if _index != -1:
tmpData = data[:_index]
else:
tmpData = data[:index]
#tmpData should not be empty.
if tmpData:
textNode = HtmlDomNode("text")
textNode.setText(tmpData)
textNode.pos = pos
pos += 1
if len(nodeStack) > 0:
nodeStack[ -1 ].append( textNode )
textNode.setAncestor( nodeStack[::-1] )
self.domNodesList.append( textNode )
self.registerNode( textNode.nodeName, textNode )
if _index != -1:
data = data[_index:]
else:
data = data[index:]
else:
pass
#end of a tag
if data.find("</") == 0:
match = endTag.search( data )
data = data[len(match.group()):]
try:
nodeStack.pop()
continue
except IndexError:
nodeStack = []
#start of a tag.
if data.find("<") == 0:
match = startTag.search( data )
if not match:
#Fail silently
continue
#match.group(1) will contain the element name
elementName = match.group(1)
#new addition: added lower function to the element name.
domNode = HtmlDomNode( elementName.lower(), 1 )
domNode.pos = pos
pos += 1
attr = match.group(2)
if attr:
#converting multispaces into single space.for easy handling of attributes
attr = whiteSpace.sub( ' ', attr.strip() )
attr = attributeSplitter.findall( attr )
attrDict = {}
for attrName,attrValues in attr:
attrDict[attrName] = attrValues.split()
domNode.setAttributes( attrDict )
if len(nodeStack) > 0:
# nodeStack[ -1 ] is a HtmlDomNode object
nodeStack[ -1 ].append( domNode )
#setting ancestor list
domNode.setAncestor( nodeStack[::-1] )
#push the current node into the stack.so now domNode becomes the current parent node.
#if the current node is an empty element,do not push the element into the stack.
if not self.xml_file:
if elementName not in emptyElements:
nodeStack.append( domNode )
elif match.group().find( "/>" ) == -1:
nodeStack.append( domNode )
else:
domNode.setAncestor( nodeStack )
# nodeStack is a list
nodeStack.append( domNode )
self.referenceToRootElement = domNode
self.registerNode( domNode.nodeName, domNode )
data = data[len(match.group()):]
else:
domNode = HtmlDomNode( "text" )
domNode.pos = pos
pos += 1
if index == -1:
domNode.setText( data )
data = data[ len( data ): ]
else:
domNode.setText( data[ :index ] )
data = data[ index: ]
self.registerNode( domNode.nodeName, domNode )
self.domNodesList.append( domNode )
def registerNode( self, nodeName, domNode ):
if self.domNodes.get(nodeName,None):
#self.domNodes[nodeName].append( domNode )
if domNode not in self.domNodes[ nodeName ]:
self.domNodes[nodeName].append( domNode )
# self.domNodes[ nodeName ] += self.getUniqueNodes( self.domNodes[ nodeName ], [ domNode ] )
else:
self.domNodes[ nodeName ] = [domNode]
def updateDomNodes( self, newDomNodes ):
for nodeName in newDomNodes:
self.domNodes[nodeName] += newDomNodes[nodeName]
def removeFromDomDict( self, node ):
if self.domNodes.get( node.nodeName, None ):
try:
pos = self.domNodes[ node.nodeName ].index( node )
del self.domNodes[ node.nodeName ][ pos ]
except ValueError:
pass
def getDomDict(self):
return self.domNodes
def domDictToList(self, no_text_node = True ):
n = []
for nodeName in self.domNodes:
for selectedNode in self.domNodes[nodeName]:
#Converting the dictionary into a list of values.
self.domNodesList.append( selectedNode )
if not no_text_node:
if selectedNode.nodeType == 1:
n.append( selectedNode )
self.domNodesList = list( set( self.domNodesList ) )
if not self.sorted:
self.domNodesList = sorted( self.domNodesList, key = lambda x: x.pos )
self.sorted = True
if not no_text_node:
return sorted( n, key = lambda x: x.pos )
return self.domNodesList
#new edition nList=[]
#this addition is for find function for HtmlNodeList
def find(self,selectors,nList=[]):
classSelector = []
idSelector = []
attributeSelector = {}
attributeSelectorFlags = {
'$':False,'^':False,'*':False,'noVal':False,"~":False
}
selectorMethod = {'+':False,'>':False}
attr_list = []
#new edition
nodeList = nList
_index = -1
# the following line is required for handling following kinds of inputs
# "div+a" getConverted into "div + a". Now it is easy to split on spaces.
selectors = re.sub(r'([+>])',r' \1 ',selectors)
#normalizing the inputs.
selectors = whiteSpace.sub( ' ', selectors )
selectors = selectors.split()
data = ""
elemName = ""
for value in selectors:
_index += 1
if value == '+' or value == '>':
selectorMethod[value] = True
continue
match = selector.search( value )
if match:
elemName = match.group(1)
data = match.group(2)
invalid = 0
while data and invalid != 100:
invalid += 1
match = newSelector.search( data )
if match:
data = match.group(2)
#class selector
if match.group(1).find(".") == 0:
index = match.group(1).find(".")
classSelector.append( match.group(1)[index+1:] )
#id selector
elif match.group(1).find("#") == 0:
index = match.group(1).find("#")
idSelector.append( match.group(1)[index +1:] )
# attribute selector
elif match.group(1).find("[") == 0:
index = match.group(1).find("]")
attr = match.group(1)[1:][:-1]
attrMatch = re.search( attributeSubStringSelector, attr )
if attrMatch:
attributeSelectorFlags[attrMatch.group(1)] = True
_index = attr.find(attrMatch.group(1))
attr = attr[:_index - len(attr)] + attr[_index + 1:]
attr = attr.split("=")
elif attr.find("=") == -1:
#Only attribute name is given not the value.
attributeSelectorFlags['noVal'] = True
attr = attr.split()
attr.append('')
else:
attr = attr.split("=")
#new addition
attr[1] = re.sub(r'[\'\"]?','',attr[1])
#new addition
attributeSelector[attr[0]] = attr[1]
if attr[ 1 ] == '':
attributeSelectorFlags[ "noVal" ] = True
attr_list.append( ( dict( attributeSelector ), dict( attributeSelectorFlags ) ) )
attributeSelector = {}
attributeSelectorFlags = {
'$':False,'^':False,'*':False,'noVal':False,"~":False
}
if invalid == 100:
raise Exception( "Invalid regular expression" )
else:
invalid = 0
if elemName:
if elemName == "*" and _index == 0:
nodes = self.domDictToList( no_text_node = False )
nodeList = []
elif elemName == "*":
nodes = self.domDictToList( no_text_node = False )
else:
nodes = self.domNodes.get( elemName, [] )
else:
if classSelector:
nodes = self.getNodesWithClassOrId(classSelector[-1],selectType='class')
elif idSelector:
nodes = self.getNodesWithClassOrId(idSelector[-1],selectType='id')
elif attr_list:
nodes = []
#new Addition:Mon 13 Feb
for a_s, a_f in attr_list:
nodes += self.getNodesWithAttributes( a_s, a_f )
nodes = list( set( nodes ) )
tmpList = []
method = ''
for node in nodeList:
if selectorMethod['+']:
method = '+'
for selectedNode in nodes:
if node.nextSiblingNode == selectedNode:
tmpList.append( selectedNode )
tmpList = list( set( tmpList ) )
elif selectorMethod['>']:
method = '>'
for selectedNode in nodes:
if selectedNode in node.children:
tmpList.append( selectedNode )
tmpList = list( set( tmpList ) )
else:
for selectedNode in nodes:
if not selectedNode.ancestorList:
selectedNode.generateAncestorList()
if node in selectedNode.ancestorList:
tmpList.append( selectedNode )
tmpList = list( set( tmpList ) )
if method != '':
selectorMethod[ method ] = False
method = ''
if not nodeList:
tmpList = nodes
nodes = tmpList
nodeList = []
for node in nodes:
nodeAccepted = True
for value in classSelector:
if value not in node.attributes.get('class',[]):
nodeAccepted = False
break
if nodeAccepted:
for value in idSelector:
if value not in node.attributes.get('id',[]):
nodeAccepted = False
break
if nodeAccepted:
for a_s, a_f in attr_list:
nodeAccepted = self.getNodesWithAttributes( a_s, a_f, [node] )
if not nodeAccepted:
break
if nodeAccepted:
nodeList.append(node)
classSelector = []
idSelector = []
attributeSelector = {}
attributeSelectorFlags = {'$':False,'^':False,'*':False,'noVal':False}
attr_list = []
if not nodeList:
break
nodeList = sorted( nodeList, key = lambda x : x.pos )
return HtmlNodeList( nodeList, self )
def getNodesWithClassOrId( self,className="",nodeList = None,selectType=""):
tmpList = []
for nodeName in self.domNodes:
[ tmpList.append( selectedNode ) for selectedNode in self.domNodes[nodeName] if className in selectedNode.attributes.get(selectType,['']) ]
return tmpList
def getNodesWithAttributes( self, attributeSelector,attributeSelectorFlags,nodeList = None):
if not self.sorted:
self.domDictToList()
tmpList = self.domNodesList
if nodeList:
tmpList = nodeList
key,attrValue = list(attributeSelector.items())[0]
newList = []
for node in tmpList:
nodeAccepted = True
if attributeSelectorFlags['$']:
#if attributeSelector[key] not in node.attributes.get(key,[''])[-1][len(node.attributes.get(key,[''])[-1])::-1]:
if attributeSelector[key] != node.attributes.get(key,[''])[-1]:
nodeAccepted = False
elif attributeSelectorFlags['^']:
if attributeSelector[key] not in node.attributes.get(key,[''])[0]:
nodeAccepted = False
elif attributeSelectorFlags['*']:
if attributeSelector[key] not in " ".join(node.attributes.get(key,[])):
nodeAccepted = False
elif attributeSelectorFlags['noVal']:
if key not in node.attributes:
nodeAccepted = False
elif attributeSelectorFlags[ "~" ]:
if attributeSelector[key] not in node.attributes.get( key, [] ):
nodeAccepted = False
elif attributeSelector[key] != " ".join(node.attributes.get(key,[])):
nodeAccepted = False
if nodeAccepted:
newList.append(node)
return newList
def getUniqueNodes(self,srcList, newList ):
tmpList = []
for selectedNode in newList:
if selectedNode not in srcList:
tmpList.append( selectedNode )
return tmpList
def getEncoding( self, response ):
encoding = 'utf-8'
for key,val in response.headers.items():
if key == 'Content-Type':
encoding = val.split(";")
try:
encoding = encoding[1].split('=')[1].strip()
except IndexError:
encoding = 'utf-8'
break
break
return encoding
class HtmlNodeList:
def __init__( self, nodeList,dom,prevNodeList=[],prevObject = None):
self.nodeList = nodeList
self.htmlDom = dom
# new addition
self.len = len( self.nodeList )
# used for iteration
self.counter = 0
self.previousNodeList = prevNodeList
if not prevObject:
self.referenceToPreviousNodeListObject = self
else:
self.referenceToPreviousNodeListObject = prevObject
def __iter__( self ):
self.counter = 0
return self
def __next__( self ):
if self.counter >= self.len:
raise StopIteration
else:
tmpObj = self.eq( self.counter )
self.counter += 1
return tmpObj
def __getitem__( self, index ):
if isinstance( index, int ):
return self.eq( index )
elif isinstance( index, slice ):
return HtmlNodeList( self.nodeList[ index ], self.htmlDom, self.nodeList, self )
def children(self, selector = None, all_children = False):
childrenList = []
if not all_children:
for node in self.nodeList:
[ childrenList.append(child) for child in node.children if child.nodeType == 1]
else:
for node in self.nodeList:
[ childrenList.append(child) for child in node.children ]
if selector:
return HtmlNodeList( childrenList, self.htmlDom, self.nodeList, self ).filter( selector )
else:
childrenList = sorted( childrenList, key = lambda x: x.pos )
return HtmlNodeList( childrenList,self.htmlDom,self.nodeList,self)
def html( self, data = None ):
if not data:
htmlStr = ""
for node in self.nodeList:
htmlStr += node.html()
return htmlStr
else:
for node in self.nodeList:
for child_node in node.children:
node.remove( child_node )
self.htmlDom.removeFromDomDict( child_node )
del child_node
node.children = []
self.append( data )
return self
def text( self, data = None ):
if not data:
textStr = ""
for node in self.nodeList:
textStr += node.getText()
return textStr
else:
for node in self.nodeList:
for child_node in node.children:
node.remove( child_node )
self.htmlDom.removeFromDomDict( child_node )
del child_node
node.children = []
self.append( data )
return self
def attr( self, attrName, val = False):
if len( self.nodeList ) > 0 and not val:
return self.nodeList[0].attr( attrName, val )
elif val:
for node in self.nodeList:
node.attr( attrName, val )
return self
else:
raise IndexError
def removeAttr( self, attrName ):
for node in self.nodeList:
node.removeAttr( attrName )
return self
def filter(self,selector):
nList = self.htmlDom.find( selector )
tmpList = []
for node in self.nodeList:
if node in nList.nodeList:
tmpList += self.getUniqueNodes( tmpList, [node] )
tmpList = sorted( tmpList, key = lambda x : x.pos )
return HtmlNodeList( tmpList,self.htmlDom, self.nodeList,self)
def _not(self,selector ):
nList = self.htmlDom.find( selector )
tmpList = []
for node in self.nodeList:
if node not in nList.nodeList:
tmpList.append( node )
tmpList = list( set( tmpList ) )
tmpList = sorted( tmpList, key = lambda x : x.pos )
return HtmlNodeList( tmpList,self.htmlDom, self.nodeList, self )
def eq(self,index ):
if index >= -len(self.nodeList) and index < len( self.nodeList ):
return HtmlNodeList( [self.nodeList[index]], self.htmlDom, self.nodeList,self )
else:
return None
def first( self ):
return self.eq(0)
def last( self ):
return self.eq( len(self.nodeList ) - 1 )
def has(self,selector ):
nList = self.htmlDom.find( selector )
tmpList = []
for node in self.nodeList:
for selectedNode in nList.nodeList:
if not selectedNode.ancestorList:
node.generateAncestorList()
if node in selectedNode.ancestorList:
tmpList += self.getUniqueNodes( tmpList, [ node ] )
tmpList = sorted( tmpList, key = lambda x: x.pos )
return HtmlNodeList( tmpList,self.htmlDom, self.nodeList,self)
def _is(self,selector):
val = self.filter( selector )
if val.nodeList:
return True
else:
return False
def next(self, selector = None):
tmpList = []
nextNode = None
for node in self.nodeList:
nextNode = node.nextSiblingNode
while nextNode and nextNode.nodeType == 3:
nextNode = nextNode.nextSiblingNode
if nextNode:
tmpList += self.getUniqueNodes( tmpList, [ nextNode ] )
if selector:
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self ).filter( selector )
else:
tmpList = sorted( tmpList, key = lambda x: x.pos )
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList,self)
def nextAll(self, selector = None ):
tmpList = []
for node in self.nodeList:
tmpList += self.getUniqueNodes( tmpList, node.getNextSiblings() )
if selector:
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self ).filter( selector )
else:
tmpList = sorted( tmpList, key = lambda x: x.pos )
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self)
def nextUntil(self,selector):
nList = self.htmlDom.find(selector)
siblingsSet = []
tmpList = []
selectedNodeList = []
for node in self.nodeList:
#This function gets all the siblings.
tmpList = node.getNextSiblings()
for selectedNode in nList.nodeList:
try:
index = tmpList.index( selectedNode )
selectedNodeList = tmpList[:index]
siblingsSet += self.getUniqueNodes( siblingsSet, selectedNodeList )
break
except ValueError:
pass
else:
siblingsSet += self.getUniqueNodes( siblingsSet, tmpList )
siblingsSet = sorted( siblingsSet, key = lambda x: x.pos )
return HtmlNodeList( siblingsSet,self.htmlDom, self.nodeList, self)
def prev(self, selector = None ):
tmpList = []
prNode = None
for node in self.nodeList:
prevNode = node.previousSiblingNode
while prevNode and prevNode.nodeType == 3: # if its text node: loop
prevNode = prevNode.previousSiblingNode
if prevNode:
tmpList += self.getUniqueNodes( tmpList, [ prevNode ] )
if selector:
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self ).filter( selector )
else:
tmpList = sorted( tmpList, key = lambda x: x.pos )
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self)
def prevAll( self, selector = None ):
tmpList = []
for node in self.nodeList:
tmpList += self.getUniqueNodes( tmpList, node.getPreviousSiblings() )
if selector:
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self ).filter( selector )
else:
tmpList = sorted( tmpList, key = lambda x: x.pos )
return HtmlNodeList( tmpList, self.htmlDom, self.nodeList, self)
def prevUntil(self,selector):
nList = self.htmlDom.find(selector)
siblingsSet = []
tmpList = []
selectedNodeList = []
for node in self.nodeList:
#This function gets all the previous siblings.
tmpList = node.getPreviousSiblings()
for selectedNode in nList.nodeList:
try:
index = tmpList.index( selectedNode )
selectedNodeList = tmpList[:index]
siblingsSet += self.getUniqueNodes( siblingsSet, selectedNodeList )
break
except ValueError:
pass
else:
siblingsSet += self.getUniqueNodes( siblingsSet, tmpList )
siblingsSet = sorted( siblingsSet, key = lambda x: x.pos )
return HtmlNodeList( siblingsSet,self.htmlDom, self.nodeList, self )
def siblings(self,selector=None):
"""
This function gets all the siblings of each node present in the current
HtmlNodeList object.( including previous and next siblings )
"""
prevSiblingsSet = []
nextSiblingsSet = []
siblingsSet = []
for node in self.nodeList:
prevSiblingsSet = node.getPreviousSiblings()
siblingsSet += self.getUniqueNodes( siblingsSet, prevSiblingsSet )
nextSiblingsSet = node.getNextSiblings()
siblingsSet += self.getUniqueNodes( siblingsSet, nextSiblingsSet )
if selector:
return HtmlNodeList( siblingsSet, self.htmlDom, self.nodeList, self ).filter( selector )
else:
siblingsSet = sorted( siblingsSet, key = lambda x: x.pos )
return HtmlNodeList( siblingsSet, self.htmlDom, self.nodeList,self )
def parent( self, selector = None ):
"""
This function gets all the parents, not just immediate parent
of each node present in the current HtmlNodeList object.