forked from jantman/misc-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtmldata.py
1536 lines (1283 loc) · 48.9 KB
/
htmldata.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
"""
Manipulate HTML or XHTML documents.
Version 1.1.1. This source code has been placed in the
public domain by Connelly Barnes.
Features:
- Translate HTML back and forth to data structures.
This allows you to read and write HTML documents
programmably, with much flexibility.
- Extract and modify URLs in an HTML document.
- Compatible with Python 2.0 - 2.5.
See the L{examples} for a quick start.
"""
__version__ = '1.1.1'
__all__ = ['examples', 'tagextract', 'tagjoin', 'urlextract',
'urljoin', 'URLMatch']
# Define True and False for Python < 2.2.
import sys
if sys.version_info[:3] < (2, 2, 0):
exec "True = 1; False = 0"
# -------------------------------------------------------------------
# Globals
# -------------------------------------------------------------------
import re
import shlex
import string
import urllib
import urlparse
import types
# Translate text between these strings as plain text (not HTML).
_IGNORE_TAGS = [('script', '/script'),
('style', '/style')]
# Special tags where we have to look for _END_X as part of the
# HTML/XHTML parsing rules.
_BEGIN_COMMENT = '<!--'
_END_COMMENT = '-->'
_BEGIN_CDATA = '<![CDATA['
_END_CDATA = ']]>'
# Mime types that can be parsed as HTML or HTML-like.
_HTML_MIMETYPES = ['text/html', 'application/xhtml',
'application/xhtml+xml', 'text/xml',
'application/xml']
# Mime types that can be parsed as CSS.
_CSS_MIMETYPES = ['text/css']
# -------------------------------------------------------------------
# HTML <-> Data structure
# -------------------------------------------------------------------
def tagextract(doc):
"""
Convert HTML to data structure.
Returns a list. HTML tags become C{(name, keyword_dict)} tuples
within the list, while plain text becomes strings within the
list. All tag names are lowercased and stripped of whitespace.
Tags which end with forward slashes have a single forward slash
placed at the end of their name, to indicate that they are XML
unclosed tags.
Example:
>>> tagextract('<img src=hi.gif alt="hi">foo<br><br/></body>')
[('img', {'src': 'hi.gif', 'alt': 'hi'}), 'foo',
('br', {}), ('br/', {}), ('/body', {})]
Text between C{'<script>'} and C{'<style>'} is rendered directly to
plain text. This prevents rogue C{'<'} or C{'>'} characters from
interfering with parsing.
>>> tagextract('<script type="a"><blah>var x; </script>')
[('script', {'type': 'a'}), '<blah>var x; ', ('/script', {})]
Comment strings and XML directives are rendered as a single long
tag with no attributes. The case of the tag "name" is not changed:
>>> tagextract('<!-- blah -->')
[('!-- blah --', {})]
>>> tagextract('<?xml version="1.0" encoding="utf-8" ?>')
[('?xml version="1.0" encoding="utf-8" ?', {})]
>>> tagextract('<!DOCTYPE html PUBLIC etc...>')
[('!DOCTYPE html PUBLIC etc...', {})]
Greater-than and less-than characters occuring inside comments or
CDATA blocks are correctly kept as part of the block:
>>> tagextract('<!-- <><><><>>..> -->')
[('!-- <><><><>>..> --', {})]
>>> tagextract('<!CDATA[[><>><>]<> ]]>')
[('!CDATA[[><>><>]<> ]]', {})]
Note that if one modifies these tags, it is important to retain the
C{"--"} (for comments) or C{"]]"} (for C{CDATA}) at the end of the
tag name, so that output from L{tagjoin} will be correct HTML/XHTML.
"""
L = _full_tag_extract(doc)
for i in range(len(L)):
if isinstance(L[i], _TextTag):
# _TextTag object.
L[i] = L[i].text
else:
# _HTMLTag object.
L[i] = (L[i].name, L[i].attrs)
return L
def _is_str(s):
"""
True iff s is a string (checks via duck typing).
"""
return hasattr(s, 'capitalize')
def tagjoin(L):
"""
Convert data structure back to HTML.
This reverses the L{tagextract} function.
More precisely, if an HTML string is turned into a data structure,
then back into HTML, the resulting string will be functionally
equivalent to the original HTML.
>>> tagjoin(tagextract(s))
(string that is functionally equivalent to s)
Three changes are made to the HTML by L{tagjoin}: tags are
lowercased, C{key=value} pairs are sorted, and values are placed in
double-quotes.
"""
if _is_str(L):
raise ValueError('got string arg, expected non-string iterable')
ans = []
for item in L:
# Check for string using duck typing.
if _is_str(item):
# Handle plain text.
ans.append(item)
elif item[0] == '--':
# Handle closing comment.
ans.append('-->')
elif item[0] == '!--':
# Handle opening comment.
ans.append('<!--')
else:
# Handle regular HTML tag.
(name, d) = item
if name[-1:] == '/':
rslash = ' /'
name = name[:-1]
else:
rslash = ''
tag_items = []
items = d.items()
items.sort()
for (key, value) in items:
if value != None:
if '"' in value and "'" in value:
raise ValueError('attribute value contains both single' +
' and double quotes')
elif '"' in value:
tag_items.append(key + "='" + value + "'")
else:
tag_items.append(key + '="' + value + '"')
else:
tag_items.append(key)
tag_items = ' '.join(tag_items)
if tag_items != '':
tag_items = ' ' + tag_items
ans.append('<' + name + tag_items + rslash + '>')
return ''.join(ans)
def _enumerate(L):
"""
Like C{enumerate}, provided for compatibility with Python < 2.3.
Returns a list instead of an iterator.
"""
return zip(range(len(L)),L)
def _ignore_tag_index(s, i):
"""
Helper routine: Find index within C{_IGNORE_TAGS}, or C{-1}.
If C{s[i:]} begins with an opening tag from C{_IGNORE_TAGS}, return
the index. Otherwise, return C{-1}.
"""
for (j, (a, b)) in _enumerate(_IGNORE_TAGS):
if s[i:i+len(a)+1].lower() == '<' + a:
return j
return -1
def _html_split(s):
"""
Helper routine: Split string into a list of tags and non-tags.
>>> html_split(' blah <tag text> more </tag stuff> ')
[' blah ', '<tag text>', ' more ', '</tag stuff>', ' ']
Tags begin with C{'<'} and end with C{'>'}.
The identity C{''.join(L) == s} is always satisfied.
Exceptions to the normal parsing of HTML tags:
C{'<script>'}, C{'<style>'}, and HTML comment tags ignore all HTML
until the closing pair, and are added as three elements:
>>> html_split(' blah<style><<<><></style><!-- hi -->' +
... ' <script language="Javascript"></>a</script>end')
[' blah', '<style>', '<<<><>', '</style>', '<!--', ' hi ', '-->',
' ', '<script language="Javascript">', '</>a', '</script>', 'end']
"""
s_lower = s.lower()
L = []
i = 0 # Index of char being processed
while i < len(s):
c = s[i]
if c == '<':
# Left bracket, handle various cases.
if s[i:i+len(_BEGIN_COMMENT)].startswith(_BEGIN_COMMENT):
# HTML begin comment tag, '<!--'. Scan for '-->'.
i2 = s.find(_END_COMMENT, i)
if i2 < 0:
# No '-->'. Append the remaining malformed content and stop.
L.append(s[i:])
break
else:
# Append the comment.
L.append(s[i:i2+len(_END_COMMENT)])
i = i2 + len(_END_COMMENT)
elif s[i:i+len(_BEGIN_CDATA)].startswith(_BEGIN_CDATA):
# XHTML begin CDATA tag. Scan for ']]>'.
i2 = s.find(_END_CDATA, i)
if i2 < 0:
# No ']]>'. Append the remaining malformed content and stop.
L.append(s[i:])
break
else:
# Append the CDATA.
L.append(s[i:i2+len(_END_CDATA)])
i = i2 + len(_END_CDATA)
else:
# Regular HTML tag. Scan for '>'.
orig_i = i
found = False
in_quot1 = False
in_quot2 = False
for i2 in xrange(i+1, len(s)):
c2 = s[i2]
if c2 == '"' and not in_quot1:
in_quot2 = not in_quot2
# Only turn on double quote if it's in a realistic place.
if in_quot2 and not in_quot1:
if i2 > 0 and s[i2-1] not in [' ', '\t', '=']:
in_quot2 = False
elif c2 == "'" and not in_quot2:
in_quot1 = not in_quot1
# Only turn on single quote if it's in a realistic place.
if in_quot1 and not in_quot2:
if i2 > 0 and s[i2-1] not in [' ', '\t', '=']:
in_quot1 = False
elif c2 == '>' and (not in_quot2 and not in_quot1):
found = True
break
if not found:
# No end '>'. Append the rest as text.
L.append(s[i:])
break
else:
# Append the tag.
L.append(s[i:i2+1])
i = i2 + 1
# Check whether we found a special ignore tag, eg '<script>'
tagi = _ignore_tag_index(s, orig_i)
if tagi >= 0:
# It's an ignore tag. Scan for the end tag.
i2 = s_lower.find('<' + _IGNORE_TAGS[tagi][1], i)
if i2 < 0:
# No end tag. Append the rest as text.
L.append(s[i2:])
break
else:
# Append the text sandwiched between the tags.
L.append(s[i:i2])
# Catch the closing tag with the next loop iteration.
i = i2
else:
# Not a left bracket, append text up to next left bracket.
i2 = s.find('<', i)
if i2 < 0:
# No left brackets, append the rest as text.
L.append(s[i:])
break
else:
L.append(s[i:i2])
i = i2
return L
def _shlex_split(s):
"""
Like C{shlex.split}, but reversible, and for HTML.
Splits a string into a list C{L} of strings. List elements
contain either an HTML tag C{name=value} pair, an HTML name
singleton (eg C{"checked"}), or whitespace.
The identity C{''.join(L) == s} is always satisfied.
>>> _shlex_split('a=5 b="15" name="Georgette A"')
['a=5', ' ', 'b="15"', ' ', 'name="Georgette A"']
>>> _shlex_split('a = a5 b=#b19 name="foo bar" q="hi"')
['a = a5', ' ', 'b=#b19', ' ', 'name="foo bar"', ' ', 'q="hi"']
>>> _shlex_split('a="9"b="15"')
['a="9"', 'b="15"']
"""
ans = []
i = 0
while i < len(s):
c = s[i]
if c in string.whitespace:
# Whitespace. Add whitespace while found.
for i2 in range(i, len(s)):
if s[i2] not in string.whitespace:
break
# Include the entire string if the last char is whitespace.
if s[i2] in string.whitespace:
i2 += 1
ans.append(s[i:i2])
i = i2
else:
# Match 'name = "value"'
c = re.compile(r'[^ \t\n\r\f\v"\']+\s*\=\s*"[^"]*"')
m = c.match(s, i)
if m:
ans.append(s[i:m.end()])
i = m.end()
continue
# Match "name = 'value'"
c = re.compile(r'[^ \t\n\r\f\v"\']+\s*\=\s*\'[^\']*\'')
m = c.match(s, i)
if m:
ans.append(s[i:m.end()])
i = m.end()
continue
# Match 'name = value'
c = re.compile(r'[^ \t\n\r\f\v"\']+\s*\=\s*[^ \t\n\r\f\v"\']*')
m = c.match(s, i)
if m:
ans.append(s[i:m.end()])
i = m.end()
continue
# Match 'name'
c = re.compile(r'[^ \t\n\r\f\v"\']+')
m = c.match(s, i)
if m:
ans.append(s[i:m.end()])
i = m.end()
continue
# Couldn't match anything so far, so it's likely that the page
# has malformed quotes inside a tag. Add leading quotes
# and spaces to the previous field until we see something.
subadd = []
while i < len(s) and s[i] in ['"', "'", ' ', '\t']:
subadd.append(s[i])
i += 1
# Add whatever we could salvage from the situation and move on.
if len(subadd) > 0:
ans.append(''.join(subadd))
else:
# We totally failed at matching this character, so add it
# as a separate item and move on.
ans.append(s[i])
return ans
def _test_shlex_split():
"""
Unit test for L{_shlex_split}.
"""
assert _shlex_split('') == []
assert _shlex_split(' ') == [' ']
assert _shlex_split('a=5 b="15" name="Georgette A"') == \
['a=5', ' ', 'b="15"', ' ', 'name="Georgette A"']
assert _shlex_split('a=cvn b=32vsd c= 234jk\te d \t="hi"') == \
['a=cvn', ' ', 'b=32vsd', ' ', 'c= 234jk', '\t', 'e', ' ',
'd \t="hi"']
assert _shlex_split(' a b c d=e f g h i="jk" l mno = p ' + \
'qr = "st"') == \
[' ', 'a', ' ', 'b', ' ', 'c', ' ', 'd=e', ' ', 'f', ' ', \
'g', ' ', 'h', ' ', 'i="jk"', ' ', 'l', ' ', 'mno = p', \
' ', 'qr = "st"']
assert _shlex_split('a=5 b="9"c="15 dfkdfkj "d="25"') == \
['a=5', ' ', 'b="9"', 'c="15 dfkdfkj "', 'd="25"']
assert _shlex_split('a=5 b="9"c="15 dfkdfkj "d="25" e=4') == \
['a=5', ' ', 'b="9"', 'c="15 dfkdfkj "', 'd="25"', ' ', \
'e=4']
assert _shlex_split('a=5 b=\'9\'c=\'15 dfkdfkj \'d=\'25\' e=4') == \
['a=5', ' ', 'b=\'9\'', 'c=\'15 dfkdfkj \'', 'd=\'25\'', \
' ', 'e=4']
def _tag_dict(s):
"""
Helper routine: Extracts a dict from an HTML tag string.
>>> _tag_dict('bgcolor=#ffffff text="#000000" blink')
({'bgcolor':'#ffffff', 'text':'#000000', 'blink': None},
{'bgcolor':(0,7), 'text':(16,20), 'blink':(31,36)},
{'bgcolor':(8,15), 'text':(22,29), 'blink':(36,36)})
Returns a 3-tuple. First element is a dict of
C{(key, value)} pairs from the HTML tag. Second element
is a dict mapping keys to C{(start, end)} indices of the
key in the text. Third element maps keys to C{(start, end)}
indices of the value in the text.
Names are lowercased.
Raises C{ValueError} for unmatched quotes and other errors.
"""
d = _shlex_split(s)
attrs = {}
key_pos = {}
value_pos = {}
start = 0
for item in d:
end = start + len(item)
equals = item.find('=')
if equals >= 0:
# Contains an equals sign.
(k1, k2) = (start, start + equals)
(v1, v2) = (start + equals + 1, start + len(item))
# Strip spaces.
while k1 < k2 and s[k1] in string.whitespace: k1 += 1
while k1 < k2 and s[k2-1] in string.whitespace: k2 -= 1
while v1 < v2 and s[v1] in string.whitespace: v1 += 1
while v1 < v2 and s[v2-1] in string.whitespace: v2 -= 1
# Strip one pair of double quotes around value.
if v1 < v2 - 1 and s[v1] == '"' and s[v2-1] == '"':
v1 += 1
v2 -= 1
# Strip one pair of single quotes around value.
if v1 < v2 - 1 and s[v1] == "'" and s[v2-1] == "'":
v1 += 1
v2 -= 1
(key, value) = (s[k1:k2].lower(), s[v1:v2])
# Drop bad keys and values.
if '"' in key or "'" in key:
continue
if '"' in value and "'" in value:
continue
attrs[key] = value
key_pos[key] = (k1, k2)
value_pos[key] = (v1, v2)
elif item.split() == []:
# Whitespace. Ignore it.
pass
else:
# A single token, like 'blink'.
key = item.lower()
# Drop bad keys.
if '"' in key or "'" in key:
continue
attrs[key] = None
key_pos[key] = (start, end)
value_pos[key] = (end, end)
start = end
return (attrs, key_pos, value_pos)
def _test_tag_dict():
"""
Unit test for L{_tag_dict}.
"""
assert _tag_dict('') == ({}, {}, {})
assert _tag_dict(' \t\r \n\n \r\n ') == ({}, {}, {})
assert _tag_dict('bgcolor=#ffffff text="#000000" blink') == \
({'bgcolor':'#ffffff', 'text':'#000000', 'blink': None},
{'bgcolor':(0,7), 'text':(16,20), 'blink':(31,36)},
{'bgcolor':(8,15), 'text':(22,29), 'blink':(36,36)})
assert _tag_dict("bgcolor='#ffffff'text='#000000' blink") == \
({'bgcolor':'#ffffff', 'text':'#000000', 'blink': None},
{'bgcolor':(0,7), 'text':(17,21), 'blink':(32,37)},
{'bgcolor':(9,16), 'text':(23,30), 'blink':(37,37)})
s = ' \r\nbg = val text \t= "hi you" name\t e="5"\t\t\t\n'
(a, b, c) = _tag_dict(s)
assert a == {'text': 'hi you', 'bg': 'val', 'e': '5', 'name': None}
for key in a.keys():
assert s[b[key][0]:b[key][1]] == key
if a[key] != None:
assert s[c[key][0]:c[key][1]] == a[key]
def _full_tag_extract(s):
"""
Like L{tagextract}, but different return format.
Returns a list of L{_HTMLTag} and L{_TextTag} instances.
The return format is very inconvenient for manipulating HTML, and
only will be useful if you want to find the exact locations where
tags occur in the original HTML document.
"""
L = _html_split(s)
# Starting position of each L[i] in s.
Lstart = [0] * len(L)
for i in range(1, len(L)):
Lstart[i] = Lstart[i-1] + len(L[i-1])
class NotTagError(Exception): pass
for (i, text) in _enumerate(L):
try:
# Is it an HTML tag?
is_tag = False
if len(text) >= 2 and text[0] == '<' and text[-1] == '>':
# Turn HTML tag text into (name, keyword_dict) tuple.
is_tag = True
is_special = False
if len(text) >= 2 and (text[1] == '!' or text[1] == '?'):
is_special = True
if is_special:
# A special tag such as XML directive or <!-- comment -->
pos = (Lstart[i], Lstart[i] + len(L[i]))
# Wrap inside an _HTMLTag object.
L[i] = _HTMLTag(pos, text[1:-1].strip(), {}, {}, {})
elif is_tag:
# If an HTML tag, strip brackets and handle what's left.
# Strip off '<>' and update offset.
orig_offset = 0
if len(text) >= 1 and text[0] == '<':
text = text[1:]
orig_offset = 1
if len(text) >= 1 and text[-1] == '>':
text = text[:-1]
if len(text) > 0 and text[-1] == '/':
rslash = True
text = text[:-1]
else:
rslash = False
m = re.search(r'\s', text)
first_space = -1
if m:
first_space = m.start()
if first_space < 0:
(name, dtext) = (text, '')
else:
name = text[:first_space]
dtext = text[first_space+1:len(text)]
# Position of dtext relative to original text.
dtext_offset = len(name) + 1 + orig_offset # +1 for space.
# Lowercase everything except XML directives and comments.
if not name.startswith('!') and not name.startswith('?'):
name = name.strip().lower()
if rslash:
name += '/'
# Strip off spaces, and update dtext_offset as appropriate.
orig_dtext = dtext
dtext = dtext.strip()
dtext_offset += orig_dtext.index(dtext)
(attrs, key_pos, value_pos) = _tag_dict(dtext)
# Correct offsets in key_pos and value_pos.
for key in attrs.keys():
key_pos[key] = (key_pos[key][0]+Lstart[i]+dtext_offset,
key_pos[key][1]+Lstart[i]+dtext_offset)
value_pos[key] = (value_pos[key][0]+Lstart[i]+dtext_offset,
value_pos[key][1]+Lstart[i]+dtext_offset)
pos = (Lstart[i], Lstart[i] + len(L[i]))
# Wrap inside an _HTMLTag object.
L[i] = _HTMLTag(pos, name, attrs, key_pos, value_pos)
else:
# Not an HTML tag.
raise NotTagError
except NotTagError:
# Wrap non-HTML strings inside a _TextTag object.
pos = (Lstart[i], Lstart[i] + len(L[i]))
L[i] = _TextTag(pos, L[i])
return L
class _HTMLTag:
"""
HTML tag extracted by L{_full_tag_extract}.
@ivar pos: C{(start, end)} indices of the entire tag in the
HTML document.
@ivar name: Name of tag. For example, C{'img'}.
@ivar attrs: Dictionary mapping tag attributes to corresponding
tag values.
Example:
>>> tag = _full_tag_extract('<a href="d.com">')[0]
>>> tag.attrs
{'href': 'd.com'}
Surrounding quotes are stripped from the values.
@ivar key_pos: Key position dict.
Maps the name of a tag attribute to C{(start, end)}
indices for the key string in the C{"key=value"}
HTML pair. Indices are absolute, where 0 is the
start of the HTML document.
Example:
>>> tag = _full_tag_extract('<a href="d.com">')[0]
>>> tag.key_pos['href']
(3, 7)
>>> '<a href="d.com">'[3:7]
'href'
@ivar value_pos: Value position dict.
Maps the name of a tag attribute to C{(start, end)}
indices for the value in the HTML document string.
Surrounding quotes are excluded from this range.
Indices are absolute, where 0 is the start of the
HTML document.
Example:
>>> tag = _full_tag_extract('<a href="d.com">')[0]
>>> tag.value_pos['href']
(9, 14)
>>> '<a href="d.com">'[9:14]
'd.com'
"""
def __init__(self, pos, name, attrs, key_pos, value_pos):
"""
Create an _HTMLTag object.
"""
self.pos = pos
self.name = name
self.attrs = attrs
self.key_pos = key_pos
self.value_pos = value_pos
class _TextTag:
"""
Text extracted from an HTML document by L{_full_tag_extract}.
@ivar text: Extracted text.
@ivar pos: C{(start, end)} indices of the text.
"""
def __init__(self, pos, text):
"""
Create a _TextTag object.
"""
self.pos = pos
self.text = text
# -------------------------------------------------------------------
# URL Editing
# -------------------------------------------------------------------
# Tags within which URLs may be found.
_URL_TAGS = ['a href', 'applet archive', 'applet code',
'applet codebase', 'area href', 'base href',
'blockquote cite', 'body background', 'del cite',
'form action', 'frame longdesc', 'frame src',
'head profile', 'iframe src', 'iframe longdesc',
'img src', 'img ismap', 'img longdesc', 'img usemap',
'input src', 'ins cite', 'link href', 'object archive',
'object codebase', 'object data', 'object usemap',
'script src', 'table background', 'tbody background',
'td background', 'tfoot background', 'th background',
'thead background', 'tr background']
_URL_TAGS = map(lambda s: tuple(s.split()), _URL_TAGS)
def _finditer(pattern, string):
"""
Like C{re.finditer}, provided for compatibility with Python < 2.3.
Returns a list instead of an iterator. Otherwise the return format
is identical to C{re.finditer} (except possibly in the details of
empty matches).
"""
compiled = re.compile(pattern)
ans = []
start = 0
while True:
m = compiled.search(string, start)
if m:
ans.append(m)
else:
return ans
m_start = m.start(m.lastindex)
m_end = m.end(m.lastindex)
if m_end > m_start:
start = m_end
else:
start += 1
def _remove_comments(doc):
"""
Replaces commented out characters with spaces in a CSS document.
"""
ans = []
i = 0
while True:
i2 = doc.find('/*', i)
if i2 < 0:
ans += [doc[i:]]
break
ans += [doc[i:i2]]
i3 = doc.find('*/', i2+1)
if i3 < 0:
i3 = len(doc) - 2
ans += [' ' * (i3 - i2 + 2)]
i = i3 + 2
return ''.join(ans)
def _test_remove_comments():
"""
Unit test for L{_remove_comments}.
"""
s = '/*d s kjlsdf */*//*/*//**/**/*//**/a' * 50
assert len(_remove_comments(s)) == len(s)
s = '/**/' * 50 + '/*5845*/*/*//*/**/dfd'+'/*//**//'
assert len(_remove_comments(s)) == len(s)
s = 'a/**/' * 50 + '/**//**/////***/****/*//**//*/' * 5
assert len(_remove_comments(s)) == len(s)
s = 'hi /* foo */ hello /* bar!!!!! \n\n */ there!'
assert _remove_comments(s) == \
'hi hello there!'
def urlextract(doc, siteurl=None, mimetype='text/html'):
"""
Extract URLs from HTML or stylesheet.
Extracts only URLs that are linked to or embedded in the document.
Ignores plain text URLs that occur in the non-HTML part of the
document.
Returns a list of L{URLMatch} objects.
>>> L = urlextract('<img src="a.gif"><a href="www.google.com">')
>>> L[0].url
'a.gif'
>>> L[1].url
'www.google.com'
If C{siteurl} is specified, all URLs are made into absolute URLs
by assuming that C{doc} is located at the URL C{siteurl}.
>>> doc = '<img src="a.gif"><a href="/b.html">'
>>> L = urlextract(doc, 'http://www.python.org/~guido/')
>>> L[0].url
'http://www.python.org/~guido/a.gif'
>>> L[1].url
'http://www.python.org/b.html'
If C{mimetype} is C{"text/css"}, the document will be parsed
as a stylesheet.
If a stylesheet is embedded inside an HTML document, then
C{urlextract} will extract the URLs from both the HTML and the
stylesheet.
"""
mimetype = mimetype.lower()
if mimetype.split()[0] in _CSS_MIMETYPES:
doc = _remove_comments(doc)
# Match URLs within CSS stylesheet.
# Match url(blah) or url('blah') or url("blah").
L = _finditer(
r'''url\s*\(([^\r\n\("']*?)\)|''' +
r'''url\s*\(\s*"([^\r\n]*?)"\s*\)|''' +
r'''url\s*\(\s*'([^\r\n]*?)'\s*\)|''' +
r'''@import\s+([^ \t\r\n"';@\(\)]+)[^\r\n;@\(\)]*[\r\n;]|''' +
r'''@import\s+'([^ \t\r\n"';@\(\)]+)'[^\r\n;@\(\)]*[\r\n;]|''' +
r'''@import\s+"([^ \t\r\n"';\(\)']+)"[^\r\n;@\(\)]*[\r\n;]''',
doc + ';\n')
L = [(x.start(x.lastindex), x.end(x.lastindex)) for x in L]
ans = []
for (s, e) in L:
e = min(e, len(doc))
if e > s:
ans.append(URLMatch(doc, s, e, siteurl, False, True))
elif mimetype.split()[0] in _HTML_MIMETYPES:
# Match URLs within HTML document.
ans = []
L = _full_tag_extract(doc)
item = None
for i in range(len(L)):
prev_item = item
item = L[i]
# Handle string item (text) or tuple item (tag).
if isinstance(item, _TextTag):
# Current item is text.
if isinstance(prev_item, _HTMLTag) and prev_item.name == \
'style':
# And previous item is <style>. Process a stylesheet.
temp = urlextract(item.text, siteurl, 'text/css')
# Offset indices and add to ans.
for j in range(len(temp)):
temp[j].start += item.pos[0]
temp[j].end += item.pos[0]
ans += temp
else:
# Regular text. Ignore.
pass
else:
# Current item is a tag.
if item.attrs.has_key('style'):
# Process a stylesheet embedded in the 'style' attribute.
temp = urlextract(item.attrs['style'], siteurl, 'text/css')
# Offset indices and add to ans.
for j in range(len(temp)):
temp[j].start += item.value_pos['style'][0]
temp[j].end += item.value_pos['style'][0]
ans += temp
for (a, b) in _URL_TAGS:
if item.name.startswith(a) and b in item.attrs.keys():
# Got one URL.
url = item.attrs[b]
# FIXME: Some HTML tag wants a URL list, look up which
# tag and make it a special case.
(start, end) = item.value_pos[b]
tag_name = a
tag_attr = b
tag_attrs = item.attrs
tag_index = i
tag = URLMatch(doc, start, end, siteurl, True, False, \
tag_attr, tag_attrs, tag_index, tag_name)
ans.append(tag)
# End of 'text/html' mimetype case.
else:
raise ValueError('unknown MIME type: ' + repr(mimetype))
# Filter the answer, removing duplicate matches.
start_end_map = {}
filtered_ans = []
for item in ans:
if not start_end_map.has_key((item.start, item.end)):
start_end_map[(item.start, item.end)] = None
filtered_ans.append(item)
return filtered_ans
def _tuple_replace(s, Lindices, Lreplace):
"""
Replace slices of a string with new substrings.
Given a list of slice tuples in C{Lindices}, replace each slice
in C{s} with the corresponding replacement substring from
C{Lreplace}.
Example:
>>> _tuple_replace('0123456789',[(4,5),(6,9)],['abc', 'def'])
'0123abc5def9'
"""
ans = []
Lindices = Lindices[:]
Lindices.sort()
if len(Lindices) != len(Lreplace):
raise ValueError('lists differ in length')
for i in range(len(Lindices)-1):
if Lindices[i][1] > Lindices[i+1][0]:
raise ValueError('tuples overlap')
if Lindices[i][1] < Lindices[i][0]:
raise ValueError('invalid tuple')
if min(Lindices[i][0], Lindices[i][1]) < 0 or \
max(Lindices[i][0], Lindices[i][1]) >= len(s):
raise ValueError('bad index')
j = 0
offset = 0
for i in range(len(Lindices)):
len1 = Lindices[i][1] - Lindices[i][0]
len2 = len(Lreplace[i])
ans.append(s[j:Lindices[i][0]+offset])
ans.append(Lreplace[i])
j = Lindices[i][1]
ans.append(s[j:])
return ''.join(ans)
def _test_tuple_replace():
"""
Unit test for L{_tuple_replace}.
"""
assert _tuple_replace('',[],[]) == ''
assert _tuple_replace('0123456789',[],[]) == '0123456789'
assert _tuple_replace('0123456789',[(4,5),(6,9)],['abc', 'def'])== \
'0123abc5def9'
assert _tuple_replace('01234567890123456789', \
[(1,9),(13,14),(16,18)],['abcd','efg','hijk']) == \
'0abcd9012efg45hijk89'
def urljoin(s, L):
"""
Write back document with modified URLs (reverses L{urlextract}).
Given a list C{L} of L{URLMatch} objects obtained from
L{urlextract}, substitutes changed URLs into the original
document C{s}, and returns the modified document.
One should only modify the C{.url} attribute of the L{URLMatch}
objects. The ordering of the URLs in the list is not important.
>>> doc = '<img src="a.png"><a href="b.png">'
>>> L = urlextract(doc)
>>> L[0].url = 'foo'
>>> L[1].url = 'bar'
>>> urljoin(doc, L)
'<img src="foo"><a href="bar">'
"""
return _tuple_replace(s, [(x.start, x.end) for x in L], \
[x.url for x in L])
def examples():
"""
Examples of the C{htmldata} module.
Example 1:
Print all absolutized URLs from Google.
Here we use L{urlextract} to obtain all URLs in the document.
>>> import urllib2, htmldata
>>> url = 'http://www.google.com/'
>>> contents = urllib2.urlopen(url).read()
>>> for u in htmldata.urlextract(contents, url):
... print u.url
...
http://www.google.com/images/logo.gif
http://www.google.com/search
(More output)
Note that the second argument to L{urlextract} causes the
URLs to be made absolute with respect to that base URL.
Example 2:
Print all image URLs from Google in relative form.