blob: f230c5f163f8f380f0c4c034c5f9bf796865f9c7 [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] == '<!--':
Ezio Melotti369cbd72012-02-13 20:36:55 +0200232 # this case is actually already handled in goahead()
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200233 return self.parse_comment(i)
234 elif rawdata[i:i+3] == '<![':
235 return self.parse_marked_section(i)
236 elif rawdata[i:i+9].lower() == '<!doctype':
237 # find the closing >
Ezio Melotti369cbd72012-02-13 20:36:55 +0200238 gtpos = rawdata.find('>', i+9)
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200239 if gtpos == -1:
240 return -1
241 self.handle_decl(rawdata[i+2:gtpos])
242 return gtpos+1
243 else:
244 return self.parse_bogus_comment(i)
245
246 # Internal -- parse bogus comment, return length or -1 if not terminated
247 # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
248 def parse_bogus_comment(self, i, report=1):
249 rawdata = self.rawdata
Ezio Melottif1174432012-02-13 16:28:54 +0200250 if rawdata[i:i+2] not in ('<!', '</'):
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200251 self.error('unexpected call to parse_comment()')
252 pos = rawdata.find('>', i+2)
253 if pos == -1:
254 return -1
255 if report:
256 self.handle_comment(rawdata[i+2:pos])
257 return pos + 1
258
Fred Draked995e112008-05-20 06:08:38 +0000259 # Internal -- parse processing instr, return end or -1 if not terminated
260 def parse_pi(self, i):
261 rawdata = self.rawdata
262 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
263 match = piclose.search(rawdata, i+2) # >
264 if not match:
265 return -1
266 j = match.start()
267 self.handle_pi(rawdata[i+2: j])
268 j = match.end()
269 return j
270
271 # Internal -- handle starttag, return end or -1 if not terminated
272 def parse_starttag(self, i):
273 self.__starttag_text = None
274 endpos = self.check_for_whole_start_tag(i)
275 if endpos < 0:
276 return endpos
277 rawdata = self.rawdata
278 self.__starttag_text = rawdata[i:endpos]
279
280 # Now parse the data between i+1 and j into a tag and attrs
281 attrs = []
282 match = tagfind.match(rawdata, i+1)
283 assert match, 'unexpected call to parse_starttag()'
284 k = match.end()
285 self.lasttag = tag = rawdata[i+1:k].lower()
286
287 while k < endpos:
288 m = attrfind.match(rawdata, k)
289 if not m:
290 break
291 attrname, rest, attrvalue = m.group(1, 2, 3)
292 if not rest:
293 attrvalue = None
294 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
295 attrvalue[:1] == '"' == attrvalue[-1:]:
296 attrvalue = attrvalue[1:-1]
Ezio Melotti0f1571c2011-11-14 18:04:05 +0200297 if attrvalue:
Fred Draked995e112008-05-20 06:08:38 +0000298 attrvalue = self.unescape(attrvalue)
299 attrs.append((attrname.lower(), attrvalue))
300 k = m.end()
301
302 end = rawdata[k:endpos].strip()
303 if end not in (">", "/>"):
304 lineno, offset = self.getpos()
305 if "\n" in self.__starttag_text:
306 lineno = lineno + self.__starttag_text.count("\n")
307 offset = len(self.__starttag_text) \
308 - self.__starttag_text.rfind("\n")
309 else:
310 offset = offset + len(self.__starttag_text)
311 self.error("junk characters in start tag: %r"
312 % (rawdata[k:endpos][:20],))
313 if end.endswith('/>'):
314 # XHTML-style empty tag: <span attr="value" />
315 self.handle_startendtag(tag, attrs)
316 else:
317 self.handle_starttag(tag, attrs)
318 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200319 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000320 return endpos
321
322 # Internal -- check to see if we have a complete starttag; return end
323 # or -1 if incomplete.
324 def check_for_whole_start_tag(self, i):
325 rawdata = self.rawdata
326 m = locatestarttagend.match(rawdata, i)
327 if m:
328 j = m.end()
329 next = rawdata[j:j+1]
330 if next == ">":
331 return j + 1
332 if next == "/":
333 if rawdata.startswith("/>", j):
334 return j + 2
335 if rawdata.startswith("/", j):
336 # buffer boundary
337 return -1
338 # else bogus input
339 self.updatepos(i, j + 1)
340 self.error("malformed empty start tag")
341 if next == "":
342 # end of input
343 return -1
344 if next in ("abcdefghijklmnopqrstuvwxyz=/"
345 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
346 # end of input in or before attribute value, or we have the
347 # '/' from a '/>' ending
348 return -1
349 self.updatepos(i, j)
350 self.error("malformed start tag")
351 raise AssertionError("we should not get here!")
352
353 # Internal -- parse endtag, return end or -1 if incomplete
354 def parse_endtag(self, i):
355 rawdata = self.rawdata
356 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
357 match = endendtag.search(rawdata, i+1) # >
358 if not match:
359 return -1
Ezio Melottif1174432012-02-13 16:28:54 +0200360 gtpos = match.end()
Fred Draked995e112008-05-20 06:08:38 +0000361 match = endtagfind.match(rawdata, i) # </ + tag + >
362 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200363 if self.cdata_elem is not None:
Ezio Melottif1174432012-02-13 16:28:54 +0200364 self.handle_data(rawdata[i:gtpos])
365 return gtpos
366 # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
367 namematch = tagfind_tolerant.match(rawdata, i+2)
368 if not namematch:
369 # w3.org/TR/html5/tokenization.html#end-tag-open-state
370 if rawdata[i:i+3] == '</>':
371 return i+3
372 else:
373 return self.parse_bogus_comment(i)
374 tagname = namematch.group().lower()
375 # consume and ignore other stuff between the name and the >
376 # Note: this is not 100% correct, since we might have things like
377 # </tag attr=">">, but looking for > after tha name should cover
378 # most of the cases and is much simpler
379 gtpos = rawdata.find('>', namematch.end())
380 self.handle_endtag(tagname)
381 return gtpos+1
Ezio Melotti7e82b272011-11-01 14:09:56 +0200382
383 elem = match.group(1).lower() # script or style
384 if self.cdata_elem is not None:
385 if elem != self.cdata_elem:
Ezio Melottif1174432012-02-13 16:28:54 +0200386 self.handle_data(rawdata[i:gtpos])
387 return gtpos
Ezio Melotti7e82b272011-11-01 14:09:56 +0200388
389 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000390 self.clear_cdata_mode()
Ezio Melottif1174432012-02-13 16:28:54 +0200391 return gtpos
Fred Draked995e112008-05-20 06:08:38 +0000392
393 # Overridable -- finish processing of start+end tag: <tag.../>
394 def handle_startendtag(self, tag, attrs):
395 self.handle_starttag(tag, attrs)
396 self.handle_endtag(tag)
397
398 # Overridable -- handle start tag
399 def handle_starttag(self, tag, attrs):
400 pass
401
402 # Overridable -- handle end tag
403 def handle_endtag(self, tag):
404 pass
405
406 # Overridable -- handle character reference
407 def handle_charref(self, name):
408 pass
409
410 # Overridable -- handle entity reference
411 def handle_entityref(self, name):
412 pass
413
414 # Overridable -- handle data
415 def handle_data(self, data):
416 pass
417
418 # Overridable -- handle comment
419 def handle_comment(self, data):
420 pass
421
422 # Overridable -- handle declaration
423 def handle_decl(self, decl):
424 pass
425
426 # Overridable -- handle processing instruction
427 def handle_pi(self, data):
428 pass
429
430 def unknown_decl(self, data):
Ezio Melotti369cbd72012-02-13 20:36:55 +0200431 pass
Fred Draked995e112008-05-20 06:08:38 +0000432
433 # Internal -- helper to remove special character quoting
434 entitydefs = None
435 def unescape(self, s):
436 if '&' not in s:
437 return s
438 def replaceEntities(s):
439 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000440 try:
441 if s[0] == "#":
442 s = s[1:]
443 if s[0] in ['x','X']:
444 c = int(s[1:], 16)
445 else:
446 c = int(s)
447 return unichr(c)
448 except ValueError:
449 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000450 else:
451 # Cannot use name2codepoint directly, because HTMLParser supports apos,
452 # which is not part of HTML 4
453 import htmlentitydefs
454 if HTMLParser.entitydefs is None:
455 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
456 for k, v in htmlentitydefs.name2codepoint.iteritems():
457 entitydefs[k] = unichr(v)
458 try:
459 return self.entitydefs[s]
460 except KeyError:
461 return '&'+s+';'
462
463 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)