blob: 516bc701470e21e745c1d8a2a23f15a4547241e7 [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 Melotti0f1571c2011-11-14 18:04:05 +020026
Fred Draked995e112008-05-20 06:08:38 +000027attrfind = re.compile(
Ezio Melotti0f1571c2011-11-14 18:04:05 +020028 r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
29 r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
Fred Draked995e112008-05-20 06:08:38 +000030
31locatestarttagend = re.compile(r"""
32 <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
33 (?:\s+ # whitespace before attribute name
Ezio Melotti0f1571c2011-11-14 18:04:05 +020034 (?:(?<=['"\s])[^\s/>][^\s/=>]* # attribute name
35 (?:\s*=+\s* # value indicator
Fred Draked995e112008-05-20 06:08:38 +000036 (?:'[^']*' # LITA-enclosed value
Ezio Melotti0f1571c2011-11-14 18:04:05 +020037 |"[^"]*" # LIT-enclosed value
38 |(?!['"])[^>\s]* # bare value
Fred Draked995e112008-05-20 06:08:38 +000039 )
Ezio Melotti0f1571c2011-11-14 18:04:05 +020040 )?\s*
41 )*
42 )?
Fred Draked995e112008-05-20 06:08:38 +000043 \s* # trailing whitespace
44""", re.VERBOSE)
45endendtag = re.compile('>')
Ezio Melotti7e82b272011-11-01 14:09:56 +020046# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
47# </ and the tag name, so maybe this should be fixed
Fred Draked995e112008-05-20 06:08:38 +000048endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
49
50
51class HTMLParseError(Exception):
52 """Exception raised for all parse errors."""
53
54 def __init__(self, msg, position=(None, None)):
55 assert msg
56 self.msg = msg
57 self.lineno = position[0]
58 self.offset = position[1]
59
60 def __str__(self):
61 result = self.msg
62 if self.lineno is not None:
63 result = result + ", at line %d" % self.lineno
64 if self.offset is not None:
65 result = result + ", column %d" % (self.offset + 1)
66 return result
67
68
69class HTMLParser(markupbase.ParserBase):
70 """Find tags and other markup and call handler functions.
71
72 Usage:
73 p = HTMLParser()
74 p.feed(data)
75 ...
76 p.close()
77
78 Start tags are handled by calling self.handle_starttag() or
79 self.handle_startendtag(); end tags by self.handle_endtag(). The
80 data between tags is passed from the parser to the derived class
81 by calling self.handle_data() with the data as argument (the data
82 may be split up in arbitrary chunks). Entity references are
83 passed by calling self.handle_entityref() with the entity
84 reference as the argument. Numeric character references are
85 passed to self.handle_charref() with the string containing the
86 reference as the argument.
87 """
88
89 CDATA_CONTENT_ELEMENTS = ("script", "style")
90
91
92 def __init__(self):
93 """Initialize and reset this instance."""
94 self.reset()
95
96 def reset(self):
97 """Reset this instance. Loses all unprocessed data."""
98 self.rawdata = ''
99 self.lasttag = '???'
100 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200101 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000102 markupbase.ParserBase.reset(self)
103
104 def feed(self, data):
Éric Araujo31890bc2011-05-25 18:11:43 +0200105 r"""Feed data to the parser.
Fred Draked995e112008-05-20 06:08:38 +0000106
107 Call this as often as you want, with as little or as much text
108 as you want (may include '\n').
109 """
110 self.rawdata = self.rawdata + data
111 self.goahead(0)
112
113 def close(self):
114 """Handle any buffered data."""
115 self.goahead(1)
116
117 def error(self, message):
118 raise HTMLParseError(message, self.getpos())
119
120 __starttag_text = None
121
122 def get_starttag_text(self):
123 """Return full source of start tag: '<...>'."""
124 return self.__starttag_text
125
Ezio Melotti7e82b272011-11-01 14:09:56 +0200126 def set_cdata_mode(self, elem):
Ezio Melotti7e82b272011-11-01 14:09:56 +0200127 self.cdata_elem = elem.lower()
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200128 self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
Fred Draked995e112008-05-20 06:08:38 +0000129
130 def clear_cdata_mode(self):
131 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200132 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000133
134 # Internal -- handle data as far as reasonable. May leave state
135 # and data to be processed by a subsequent call. If 'end' is
136 # true, force handling all data as if followed by EOF marker.
137 def goahead(self, end):
138 rawdata = self.rawdata
139 i = 0
140 n = len(rawdata)
141 while i < n:
142 match = self.interesting.search(rawdata, i) # < or &
143 if match:
144 j = match.start()
145 else:
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200146 if self.cdata_elem:
147 break
Fred Draked995e112008-05-20 06:08:38 +0000148 j = n
149 if i < j: self.handle_data(rawdata[i:j])
150 i = self.updatepos(i, j)
151 if i == n: break
152 startswith = rawdata.startswith
153 if startswith('<', i):
154 if starttagopen.match(rawdata, i): # < + letter
155 k = self.parse_starttag(i)
156 elif startswith("</", i):
157 k = self.parse_endtag(i)
158 elif startswith("<!--", i):
159 k = self.parse_comment(i)
160 elif startswith("<?", i):
161 k = self.parse_pi(i)
162 elif startswith("<!", i):
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200163 k = self.parse_html_declaration(i)
Fred Draked995e112008-05-20 06:08:38 +0000164 elif (i + 1) < n:
165 self.handle_data("<")
166 k = i + 1
167 else:
168 break
169 if k < 0:
170 if end:
171 self.error("EOF in middle of construct")
172 break
173 i = self.updatepos(i, k)
174 elif startswith("&#", i):
175 match = charref.match(rawdata, i)
176 if match:
177 name = match.group()[2:-1]
178 self.handle_charref(name)
179 k = match.end()
180 if not startswith(';', k-1):
181 k = k - 1
182 i = self.updatepos(i, k)
183 continue
184 else:
Victor Stinner554a3b82010-05-24 21:33:24 +0000185 if ";" in rawdata[i:]: #bail by consuming &#
186 self.handle_data(rawdata[0:2])
187 i = self.updatepos(i, 2)
Fred Draked995e112008-05-20 06:08:38 +0000188 break
189 elif startswith('&', i):
190 match = entityref.match(rawdata, i)
191 if match:
192 name = match.group(1)
193 self.handle_entityref(name)
194 k = match.end()
195 if not startswith(';', k-1):
196 k = k - 1
197 i = self.updatepos(i, k)
198 continue
199 match = incomplete.match(rawdata, i)
200 if match:
201 # match.group() will contain at least 2 chars
202 if end and match.group() == rawdata[i:]:
203 self.error("EOF in middle of entity or char ref")
204 # incomplete
205 break
206 elif (i + 1) < n:
207 # not the end of the buffer, and can't be confused
208 # with some other construct
209 self.handle_data("&")
210 i = self.updatepos(i, i + 1)
211 else:
212 break
213 else:
214 assert 0, "interesting.search() lied"
215 # end while
Ezio Melotti00dc60b2011-11-18 18:00:40 +0200216 if end and i < n and not self.cdata_elem:
Fred Draked995e112008-05-20 06:08:38 +0000217 self.handle_data(rawdata[i:n])
218 i = self.updatepos(i, n)
219 self.rawdata = rawdata[i:]
220
Ezio Melotti4b92cc32012-02-13 16:10:44 +0200221 # Internal -- parse html declarations, return length or -1 if not terminated
222 # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
223 # See also parse_declaration in _markupbase
224 def parse_html_declaration(self, i):
225 rawdata = self.rawdata
226 if rawdata[i:i+2] != '<!':
227 self.error('unexpected call to parse_html_declaration()')
228 if rawdata[i:i+4] == '<!--':
229 return self.parse_comment(i)
230 elif rawdata[i:i+3] == '<![':
231 return self.parse_marked_section(i)
232 elif rawdata[i:i+9].lower() == '<!doctype':
233 # find the closing >
234 gtpos = rawdata.find('>', 9)
235 if gtpos == -1:
236 return -1
237 self.handle_decl(rawdata[i+2:gtpos])
238 return gtpos+1
239 else:
240 return self.parse_bogus_comment(i)
241
242 # Internal -- parse bogus comment, return length or -1 if not terminated
243 # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
244 def parse_bogus_comment(self, i, report=1):
245 rawdata = self.rawdata
246 if rawdata[i:i+2] != '<!':
247 self.error('unexpected call to parse_comment()')
248 pos = rawdata.find('>', i+2)
249 if pos == -1:
250 return -1
251 if report:
252 self.handle_comment(rawdata[i+2:pos])
253 return pos + 1
254
Fred Draked995e112008-05-20 06:08:38 +0000255 # Internal -- parse processing instr, return end or -1 if not terminated
256 def parse_pi(self, i):
257 rawdata = self.rawdata
258 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
259 match = piclose.search(rawdata, i+2) # >
260 if not match:
261 return -1
262 j = match.start()
263 self.handle_pi(rawdata[i+2: j])
264 j = match.end()
265 return j
266
267 # Internal -- handle starttag, return end or -1 if not terminated
268 def parse_starttag(self, i):
269 self.__starttag_text = None
270 endpos = self.check_for_whole_start_tag(i)
271 if endpos < 0:
272 return endpos
273 rawdata = self.rawdata
274 self.__starttag_text = rawdata[i:endpos]
275
276 # Now parse the data between i+1 and j into a tag and attrs
277 attrs = []
278 match = tagfind.match(rawdata, i+1)
279 assert match, 'unexpected call to parse_starttag()'
280 k = match.end()
281 self.lasttag = tag = rawdata[i+1:k].lower()
282
283 while k < endpos:
284 m = attrfind.match(rawdata, k)
285 if not m:
286 break
287 attrname, rest, attrvalue = m.group(1, 2, 3)
288 if not rest:
289 attrvalue = None
290 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
291 attrvalue[:1] == '"' == attrvalue[-1:]:
292 attrvalue = attrvalue[1:-1]
Ezio Melotti0f1571c2011-11-14 18:04:05 +0200293 if attrvalue:
Fred Draked995e112008-05-20 06:08:38 +0000294 attrvalue = self.unescape(attrvalue)
295 attrs.append((attrname.lower(), attrvalue))
296 k = m.end()
297
298 end = rawdata[k:endpos].strip()
299 if end not in (">", "/>"):
300 lineno, offset = self.getpos()
301 if "\n" in self.__starttag_text:
302 lineno = lineno + self.__starttag_text.count("\n")
303 offset = len(self.__starttag_text) \
304 - self.__starttag_text.rfind("\n")
305 else:
306 offset = offset + len(self.__starttag_text)
307 self.error("junk characters in start tag: %r"
308 % (rawdata[k:endpos][:20],))
309 if end.endswith('/>'):
310 # XHTML-style empty tag: <span attr="value" />
311 self.handle_startendtag(tag, attrs)
312 else:
313 self.handle_starttag(tag, attrs)
314 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200315 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000316 return endpos
317
318 # Internal -- check to see if we have a complete starttag; return end
319 # or -1 if incomplete.
320 def check_for_whole_start_tag(self, i):
321 rawdata = self.rawdata
322 m = locatestarttagend.match(rawdata, i)
323 if m:
324 j = m.end()
325 next = rawdata[j:j+1]
326 if next == ">":
327 return j + 1
328 if next == "/":
329 if rawdata.startswith("/>", j):
330 return j + 2
331 if rawdata.startswith("/", j):
332 # buffer boundary
333 return -1
334 # else bogus input
335 self.updatepos(i, j + 1)
336 self.error("malformed empty start tag")
337 if next == "":
338 # end of input
339 return -1
340 if next in ("abcdefghijklmnopqrstuvwxyz=/"
341 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
342 # end of input in or before attribute value, or we have the
343 # '/' from a '/>' ending
344 return -1
345 self.updatepos(i, j)
346 self.error("malformed start tag")
347 raise AssertionError("we should not get here!")
348
349 # Internal -- parse endtag, return end or -1 if incomplete
350 def parse_endtag(self, i):
351 rawdata = self.rawdata
352 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
353 match = endendtag.search(rawdata, i+1) # >
354 if not match:
355 return -1
356 j = match.end()
357 match = endtagfind.match(rawdata, i) # </ + tag + >
358 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200359 if self.cdata_elem is not None:
360 self.handle_data(rawdata[i:j])
361 return j
Fred Draked995e112008-05-20 06:08:38 +0000362 self.error("bad end tag: %r" % (rawdata[i:j],))
Ezio Melotti7e82b272011-11-01 14:09:56 +0200363
364 elem = match.group(1).lower() # script or style
365 if self.cdata_elem is not None:
366 if elem != self.cdata_elem:
367 self.handle_data(rawdata[i:j])
368 return j
369
370 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000371 self.clear_cdata_mode()
372 return j
373
374 # Overridable -- finish processing of start+end tag: <tag.../>
375 def handle_startendtag(self, tag, attrs):
376 self.handle_starttag(tag, attrs)
377 self.handle_endtag(tag)
378
379 # Overridable -- handle start tag
380 def handle_starttag(self, tag, attrs):
381 pass
382
383 # Overridable -- handle end tag
384 def handle_endtag(self, tag):
385 pass
386
387 # Overridable -- handle character reference
388 def handle_charref(self, name):
389 pass
390
391 # Overridable -- handle entity reference
392 def handle_entityref(self, name):
393 pass
394
395 # Overridable -- handle data
396 def handle_data(self, data):
397 pass
398
399 # Overridable -- handle comment
400 def handle_comment(self, data):
401 pass
402
403 # Overridable -- handle declaration
404 def handle_decl(self, decl):
405 pass
406
407 # Overridable -- handle processing instruction
408 def handle_pi(self, data):
409 pass
410
411 def unknown_decl(self, data):
412 self.error("unknown declaration: %r" % (data,))
413
414 # Internal -- helper to remove special character quoting
415 entitydefs = None
416 def unescape(self, s):
417 if '&' not in s:
418 return s
419 def replaceEntities(s):
420 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000421 try:
422 if s[0] == "#":
423 s = s[1:]
424 if s[0] in ['x','X']:
425 c = int(s[1:], 16)
426 else:
427 c = int(s)
428 return unichr(c)
429 except ValueError:
430 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000431 else:
432 # Cannot use name2codepoint directly, because HTMLParser supports apos,
433 # which is not part of HTML 4
434 import htmlentitydefs
435 if HTMLParser.entitydefs is None:
436 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
437 for k, v in htmlentitydefs.name2codepoint.iteritems():
438 entitydefs[k] = unichr(v)
439 try:
440 return self.entitydefs[s]
441 except KeyError:
442 return '&'+s+';'
443
444 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)