blob: 6cc9ff13bf4f22d6221f78b9b1efd9568b1d6fd5 [file] [log] [blame]
Fred Draked995e112008-05-20 06:08:38 +00001"""A parser for HTML and XHTML."""
2
3# This file is based on sgmllib.py, but the API is slightly different.
4
5# XXX There should be a way to distinguish between PCDATA (parsed
6# character data -- the normal case), RCDATA (replaceable character
7# data -- only char and entity references and end tags are special)
8# and CDATA (character data -- only end tags are special).
9
10
11import markupbase
12import re
13
14# Regular expressions used for parsing
15
16interesting_normal = re.compile('[&<]')
Fred Draked995e112008-05-20 06:08:38 +000017incomplete = re.compile('&[a-zA-Z#]')
18
19entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
20charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
21
22starttagopen = re.compile('<[a-zA-Z]')
23piclose = re.compile('>')
24commentclose = re.compile(r'--\s*>')
25tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
Ezio Melottif1174432012-02-13 16:28:54 +020026# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
27# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
28tagfind_tolerant = re.compile('[a-zA-Z][^\t\n\r\f />\x00]*')
Ezio Melotti0f1571c2011-11-14 18:04:05 +020029
Fred Draked995e112008-05-20 06:08:38 +000030attrfind = re.compile(
Ezio Melotti0f1571c2011-11-14 18:04:05 +020031 r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
32 r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
Fred Draked995e112008-05-20 06:08:38 +000033
34locatestarttagend = re.compile(r"""
35 <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
36 (?:\s+ # whitespace before attribute name
Ezio Melotti0f1571c2011-11-14 18:04:05 +020037 (?:(?<=['"\s])[^\s/>][^\s/=>]* # attribute name
38 (?:\s*=+\s* # value indicator
Fred Draked995e112008-05-20 06:08:38 +000039 (?:'[^']*' # LITA-enclosed value
Ezio Melotti0f1571c2011-11-14 18:04:05 +020040 |"[^"]*" # LIT-enclosed value
41 |(?!['"])[^>\s]* # bare value
Fred Draked995e112008-05-20 06:08:38 +000042 )
Ezio Melotti0f1571c2011-11-14 18:04:05 +020043 )?\s*
44 )*
45 )?
Fred Draked995e112008-05-20 06:08:38 +000046 \s* # trailing whitespace
47""", re.VERBOSE)
48endendtag = re.compile('>')
Ezio Melotti7e82b272011-11-01 14:09:56 +020049# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
50# </ and the tag name, so maybe this should be fixed
Fred Draked995e112008-05-20 06:08:38 +000051endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
52
53
54class HTMLParseError(Exception):
55 """Exception raised for all parse errors."""
56
57 def __init__(self, msg, position=(None, None)):
58 assert msg
59 self.msg = msg
60 self.lineno = position[0]
61 self.offset = position[1]
62
63 def __str__(self):
64 result = self.msg
65 if self.lineno is not None:
66 result = result + ", at line %d" % self.lineno
67 if self.offset is not None:
68 result = result + ", column %d" % (self.offset + 1)
69 return result
70
71
72class HTMLParser(markupbase.ParserBase):
73 """Find tags and other markup and call handler functions.
74
75 Usage:
76 p = HTMLParser()
77 p.feed(data)
78 ...
79 p.close()
80
81 Start tags are handled by calling self.handle_starttag() or
82 self.handle_startendtag(); end tags by self.handle_endtag(). The
83 data between tags is passed from the parser to the derived class
84 by calling self.handle_data() with the data as argument (the data
85 may be split up in arbitrary chunks). Entity references are
86 passed by calling self.handle_entityref() with the entity
87 reference as the argument. Numeric character references are
88 passed to self.handle_charref() with the string containing the
89 reference as the argument.
90 """
91
92 CDATA_CONTENT_ELEMENTS = ("script", "style")
93
94
95 def __init__(self):
96 """Initialize and reset this instance."""
97 self.reset()
98
99 def reset(self):
100 """Reset this instance. Loses all unprocessed data."""
101 self.rawdata = ''
102 self.lasttag = '???'
103 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200104 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000105 markupbase.ParserBase.reset(self)
106
107 def feed(self, data):
Éric Araujo31890bc2011-05-25 18:11:43 +0200108 r"""Feed data to the parser.
Fred Draked995e112008-05-20 06:08:38 +0000109
110 Call this as often as you want, with as little or as much text
111 as you want (may include '\n').
112 """
113 self.rawdata = self.rawdata + data
114 self.goahead(0)
115
116 def close(self):
117 """Handle any buffered data."""
118 self.goahead(1)
119
120 def error(self, message):
121 raise HTMLParseError(message, self.getpos())
122
123 __starttag_text = None
124
125 def get_starttag_text(self):
126 """Return full source of start tag: '<...>'."""
127 return self.__starttag_text
128
Ezio Melotti7e82b272011-11-01 14:09:56 +0200129 def set_cdata_mode(self, elem):
Ezio Melotti7e82b272011-11-01 14:09:56 +0200130 self.cdata_elem = elem.lower()
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200131 self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
Fred Draked995e112008-05-20 06:08:38 +0000132
133 def clear_cdata_mode(self):
134 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200135 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000136
137 # Internal -- handle data as far as reasonable. May leave state
138 # and data to be processed by a subsequent call. If 'end' is
139 # true, force handling all data as if followed by EOF marker.
140 def goahead(self, end):
141 rawdata = self.rawdata
142 i = 0
143 n = len(rawdata)
144 while i < n:
145 match = self.interesting.search(rawdata, i) # < or &
146 if match:
147 j = match.start()
148 else:
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200149 if self.cdata_elem:
150 break
Fred Draked995e112008-05-20 06:08:38 +0000151 j = n
152 if i < j: self.handle_data(rawdata[i:j])
153 i = self.updatepos(i, j)
154 if i == n: break
155 startswith = rawdata.startswith
156 if startswith('<', i):
157 if starttagopen.match(rawdata, i): # < + letter
158 k = self.parse_starttag(i)
159 elif startswith("</", i):
160 k = self.parse_endtag(i)
161 elif startswith("<!--", i):
162 k = self.parse_comment(i)
163 elif startswith("<?", i):
164 k = self.parse_pi(i)
165 elif startswith("<!", i):
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200166 k = self.parse_html_declaration(i)
Fred Draked995e112008-05-20 06:08:38 +0000167 elif (i + 1) < n:
168 self.handle_data("<")
169 k = i + 1
170 else:
171 break
172 if k < 0:
173 if end:
174 self.error("EOF in middle of construct")
175 break
176 i = self.updatepos(i, k)
177 elif startswith("&#", i):
178 match = charref.match(rawdata, i)
179 if match:
180 name = match.group()[2:-1]
181 self.handle_charref(name)
182 k = match.end()
183 if not startswith(';', k-1):
184 k = k - 1
185 i = self.updatepos(i, k)
186 continue
187 else:
Victor Stinner554a3b82010-05-24 21:33:24 +0000188 if ";" in rawdata[i:]: #bail by consuming &#
189 self.handle_data(rawdata[0:2])
190 i = self.updatepos(i, 2)
Fred Draked995e112008-05-20 06:08:38 +0000191 break
192 elif startswith('&', i):
193 match = entityref.match(rawdata, i)
194 if match:
195 name = match.group(1)
196 self.handle_entityref(name)
197 k = match.end()
198 if not startswith(';', k-1):
199 k = k - 1
200 i = self.updatepos(i, k)
201 continue
202 match = incomplete.match(rawdata, i)
203 if match:
204 # match.group() will contain at least 2 chars
205 if end and match.group() == rawdata[i:]:
206 self.error("EOF in middle of entity or char ref")
207 # incomplete
208 break
209 elif (i + 1) < n:
210 # not the end of the buffer, and can't be confused
211 # with some other construct
212 self.handle_data("&")
213 i = self.updatepos(i, i + 1)
214 else:
215 break
216 else:
217 assert 0, "interesting.search() lied"
218 # end while
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200219 if end and i < n and not self.cdata_elem:
Fred Draked995e112008-05-20 06:08:38 +0000220 self.handle_data(rawdata[i:n])
221 i = self.updatepos(i, n)
222 self.rawdata = rawdata[i:]
223
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200224 # Internal -- parse html declarations, return length or -1 if not terminated
225 # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
226 # See also parse_declaration in _markupbase
227 def parse_html_declaration(self, i):
228 rawdata = self.rawdata
229 if rawdata[i:i+2] != '<!':
230 self.error('unexpected call to parse_html_declaration()')
231 if rawdata[i:i+4] == '<!--':
232 return self.parse_comment(i)
233 elif rawdata[i:i+3] == '<![':
234 return self.parse_marked_section(i)
235 elif rawdata[i:i+9].lower() == '<!doctype':
236 # find the closing >
237 gtpos = rawdata.find('>', 9)
238 if gtpos == -1:
239 return -1
240 self.handle_decl(rawdata[i+2:gtpos])
241 return gtpos+1
242 else:
243 return self.parse_bogus_comment(i)
244
245 # Internal -- parse bogus comment, return length or -1 if not terminated
246 # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
247 def parse_bogus_comment(self, i, report=1):
248 rawdata = self.rawdata
Ezio Melottif1174432012-02-13 16:28:54 +0200249 if rawdata[i:i+2] not in ('<!', '</'):
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200250 self.error('unexpected call to parse_comment()')
251 pos = rawdata.find('>', i+2)
252 if pos == -1:
253 return -1
254 if report:
255 self.handle_comment(rawdata[i+2:pos])
256 return pos + 1
257
Fred Draked995e112008-05-20 06:08:38 +0000258 # Internal -- parse processing instr, return end or -1 if not terminated
259 def parse_pi(self, i):
260 rawdata = self.rawdata
261 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
262 match = piclose.search(rawdata, i+2) # >
263 if not match:
264 return -1
265 j = match.start()
266 self.handle_pi(rawdata[i+2: j])
267 j = match.end()
268 return j
269
270 # Internal -- handle starttag, return end or -1 if not terminated
271 def parse_starttag(self, i):
272 self.__starttag_text = None
273 endpos = self.check_for_whole_start_tag(i)
274 if endpos < 0:
275 return endpos
276 rawdata = self.rawdata
277 self.__starttag_text = rawdata[i:endpos]
278
279 # Now parse the data between i+1 and j into a tag and attrs
280 attrs = []
281 match = tagfind.match(rawdata, i+1)
282 assert match, 'unexpected call to parse_starttag()'
283 k = match.end()
284 self.lasttag = tag = rawdata[i+1:k].lower()
285
286 while k < endpos:
287 m = attrfind.match(rawdata, k)
288 if not m:
289 break
290 attrname, rest, attrvalue = m.group(1, 2, 3)
291 if not rest:
292 attrvalue = None
293 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
294 attrvalue[:1] == '"' == attrvalue[-1:]:
295 attrvalue = attrvalue[1:-1]
Ezio Melotti0f1571c2011-11-14 18:04:05 +0200296 if attrvalue:
Fred Draked995e112008-05-20 06:08:38 +0000297 attrvalue = self.unescape(attrvalue)
298 attrs.append((attrname.lower(), attrvalue))
299 k = m.end()
300
301 end = rawdata[k:endpos].strip()
302 if end not in (">", "/>"):
303 lineno, offset = self.getpos()
304 if "\n" in self.__starttag_text:
305 lineno = lineno + self.__starttag_text.count("\n")
306 offset = len(self.__starttag_text) \
307 - self.__starttag_text.rfind("\n")
308 else:
309 offset = offset + len(self.__starttag_text)
310 self.error("junk characters in start tag: %r"
311 % (rawdata[k:endpos][:20],))
312 if end.endswith('/>'):
313 # XHTML-style empty tag: <span attr="value" />
314 self.handle_startendtag(tag, attrs)
315 else:
316 self.handle_starttag(tag, attrs)
317 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200318 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000319 return endpos
320
321 # Internal -- check to see if we have a complete starttag; return end
322 # or -1 if incomplete.
323 def check_for_whole_start_tag(self, i):
324 rawdata = self.rawdata
325 m = locatestarttagend.match(rawdata, i)
326 if m:
327 j = m.end()
328 next = rawdata[j:j+1]
329 if next == ">":
330 return j + 1
331 if next == "/":
332 if rawdata.startswith("/>", j):
333 return j + 2
334 if rawdata.startswith("/", j):
335 # buffer boundary
336 return -1
337 # else bogus input
338 self.updatepos(i, j + 1)
339 self.error("malformed empty start tag")
340 if next == "":
341 # end of input
342 return -1
343 if next in ("abcdefghijklmnopqrstuvwxyz=/"
344 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
345 # end of input in or before attribute value, or we have the
346 # '/' from a '/>' ending
347 return -1
348 self.updatepos(i, j)
349 self.error("malformed start tag")
350 raise AssertionError("we should not get here!")
351
352 # Internal -- parse endtag, return end or -1 if incomplete
353 def parse_endtag(self, i):
354 rawdata = self.rawdata
355 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
356 match = endendtag.search(rawdata, i+1) # >
357 if not match:
358 return -1
Ezio Melottif1174432012-02-13 16:28:54 +0200359 gtpos = match.end()
Fred Draked995e112008-05-20 06:08:38 +0000360 match = endtagfind.match(rawdata, i) # </ + tag + >
361 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200362 if self.cdata_elem is not None:
Ezio Melottif1174432012-02-13 16:28:54 +0200363 self.handle_data(rawdata[i:gtpos])
364 return gtpos
365 # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
366 namematch = tagfind_tolerant.match(rawdata, i+2)
367 if not namematch:
368 # w3.org/TR/html5/tokenization.html#end-tag-open-state
369 if rawdata[i:i+3] == '</>':
370 return i+3
371 else:
372 return self.parse_bogus_comment(i)
373 tagname = namematch.group().lower()
374 # consume and ignore other stuff between the name and the >
375 # Note: this is not 100% correct, since we might have things like
376 # </tag attr=">">, but looking for > after tha name should cover
377 # most of the cases and is much simpler
378 gtpos = rawdata.find('>', namematch.end())
379 self.handle_endtag(tagname)
380 return gtpos+1
Ezio Melotti7e82b272011-11-01 14:09:56 +0200381
382 elem = match.group(1).lower() # script or style
383 if self.cdata_elem is not None:
384 if elem != self.cdata_elem:
Ezio Melottif1174432012-02-13 16:28:54 +0200385 self.handle_data(rawdata[i:gtpos])
386 return gtpos
Ezio Melotti7e82b272011-11-01 14:09:56 +0200387
388 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000389 self.clear_cdata_mode()
Ezio Melottif1174432012-02-13 16:28:54 +0200390 return gtpos
Fred Draked995e112008-05-20 06:08:38 +0000391
392 # Overridable -- finish processing of start+end tag: <tag.../>
393 def handle_startendtag(self, tag, attrs):
394 self.handle_starttag(tag, attrs)
395 self.handle_endtag(tag)
396
397 # Overridable -- handle start tag
398 def handle_starttag(self, tag, attrs):
399 pass
400
401 # Overridable -- handle end tag
402 def handle_endtag(self, tag):
403 pass
404
405 # Overridable -- handle character reference
406 def handle_charref(self, name):
407 pass
408
409 # Overridable -- handle entity reference
410 def handle_entityref(self, name):
411 pass
412
413 # Overridable -- handle data
414 def handle_data(self, data):
415 pass
416
417 # Overridable -- handle comment
418 def handle_comment(self, data):
419 pass
420
421 # Overridable -- handle declaration
422 def handle_decl(self, decl):
423 pass
424
425 # Overridable -- handle processing instruction
426 def handle_pi(self, data):
427 pass
428
429 def unknown_decl(self, data):
430 self.error("unknown declaration: %r" % (data,))
431
432 # Internal -- helper to remove special character quoting
433 entitydefs = None
434 def unescape(self, s):
435 if '&' not in s:
436 return s
437 def replaceEntities(s):
438 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000439 try:
440 if s[0] == "#":
441 s = s[1:]
442 if s[0] in ['x','X']:
443 c = int(s[1:], 16)
444 else:
445 c = int(s)
446 return unichr(c)
447 except ValueError:
448 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000449 else:
450 # Cannot use name2codepoint directly, because HTMLParser supports apos,
451 # which is not part of HTML 4
452 import htmlentitydefs
453 if HTMLParser.entitydefs is None:
454 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
455 for k, v in htmlentitydefs.name2codepoint.iteritems():
456 entitydefs[k] = unichr(v)
457 try:
458 return self.entitydefs[s]
459 except KeyError:
460 return '&'+s+';'
461
462 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)