blob: 1c6989e7d440db6ab56cd29ebd6b9da7751ed54d [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):
163 k = self.parse_declaration(i)
164 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
221 # Internal -- parse processing instr, return end or -1 if not terminated
222 def parse_pi(self, i):
223 rawdata = self.rawdata
224 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
225 match = piclose.search(rawdata, i+2) # >
226 if not match:
227 return -1
228 j = match.start()
229 self.handle_pi(rawdata[i+2: j])
230 j = match.end()
231 return j
232
233 # Internal -- handle starttag, return end or -1 if not terminated
234 def parse_starttag(self, i):
235 self.__starttag_text = None
236 endpos = self.check_for_whole_start_tag(i)
237 if endpos < 0:
238 return endpos
239 rawdata = self.rawdata
240 self.__starttag_text = rawdata[i:endpos]
241
242 # Now parse the data between i+1 and j into a tag and attrs
243 attrs = []
244 match = tagfind.match(rawdata, i+1)
245 assert match, 'unexpected call to parse_starttag()'
246 k = match.end()
247 self.lasttag = tag = rawdata[i+1:k].lower()
248
249 while k < endpos:
250 m = attrfind.match(rawdata, k)
251 if not m:
252 break
253 attrname, rest, attrvalue = m.group(1, 2, 3)
254 if not rest:
255 attrvalue = None
256 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
257 attrvalue[:1] == '"' == attrvalue[-1:]:
258 attrvalue = attrvalue[1:-1]
Ezio Melotti0f1571c2011-11-14 18:04:05 +0200259 if attrvalue:
Fred Draked995e112008-05-20 06:08:38 +0000260 attrvalue = self.unescape(attrvalue)
261 attrs.append((attrname.lower(), attrvalue))
262 k = m.end()
263
264 end = rawdata[k:endpos].strip()
265 if end not in (">", "/>"):
266 lineno, offset = self.getpos()
267 if "\n" in self.__starttag_text:
268 lineno = lineno + self.__starttag_text.count("\n")
269 offset = len(self.__starttag_text) \
270 - self.__starttag_text.rfind("\n")
271 else:
272 offset = offset + len(self.__starttag_text)
273 self.error("junk characters in start tag: %r"
274 % (rawdata[k:endpos][:20],))
275 if end.endswith('/>'):
276 # XHTML-style empty tag: <span attr="value" />
277 self.handle_startendtag(tag, attrs)
278 else:
279 self.handle_starttag(tag, attrs)
280 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200281 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000282 return endpos
283
284 # Internal -- check to see if we have a complete starttag; return end
285 # or -1 if incomplete.
286 def check_for_whole_start_tag(self, i):
287 rawdata = self.rawdata
288 m = locatestarttagend.match(rawdata, i)
289 if m:
290 j = m.end()
291 next = rawdata[j:j+1]
292 if next == ">":
293 return j + 1
294 if next == "/":
295 if rawdata.startswith("/>", j):
296 return j + 2
297 if rawdata.startswith("/", j):
298 # buffer boundary
299 return -1
300 # else bogus input
301 self.updatepos(i, j + 1)
302 self.error("malformed empty start tag")
303 if next == "":
304 # end of input
305 return -1
306 if next in ("abcdefghijklmnopqrstuvwxyz=/"
307 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
308 # end of input in or before attribute value, or we have the
309 # '/' from a '/>' ending
310 return -1
311 self.updatepos(i, j)
312 self.error("malformed start tag")
313 raise AssertionError("we should not get here!")
314
315 # Internal -- parse endtag, return end or -1 if incomplete
316 def parse_endtag(self, i):
317 rawdata = self.rawdata
318 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
319 match = endendtag.search(rawdata, i+1) # >
320 if not match:
321 return -1
322 j = match.end()
323 match = endtagfind.match(rawdata, i) # </ + tag + >
324 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200325 if self.cdata_elem is not None:
326 self.handle_data(rawdata[i:j])
327 return j
Fred Draked995e112008-05-20 06:08:38 +0000328 self.error("bad end tag: %r" % (rawdata[i:j],))
Ezio Melotti7e82b272011-11-01 14:09:56 +0200329
330 elem = match.group(1).lower() # script or style
331 if self.cdata_elem is not None:
332 if elem != self.cdata_elem:
333 self.handle_data(rawdata[i:j])
334 return j
335
336 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000337 self.clear_cdata_mode()
338 return j
339
340 # Overridable -- finish processing of start+end tag: <tag.../>
341 def handle_startendtag(self, tag, attrs):
342 self.handle_starttag(tag, attrs)
343 self.handle_endtag(tag)
344
345 # Overridable -- handle start tag
346 def handle_starttag(self, tag, attrs):
347 pass
348
349 # Overridable -- handle end tag
350 def handle_endtag(self, tag):
351 pass
352
353 # Overridable -- handle character reference
354 def handle_charref(self, name):
355 pass
356
357 # Overridable -- handle entity reference
358 def handle_entityref(self, name):
359 pass
360
361 # Overridable -- handle data
362 def handle_data(self, data):
363 pass
364
365 # Overridable -- handle comment
366 def handle_comment(self, data):
367 pass
368
369 # Overridable -- handle declaration
370 def handle_decl(self, decl):
371 pass
372
373 # Overridable -- handle processing instruction
374 def handle_pi(self, data):
375 pass
376
377 def unknown_decl(self, data):
378 self.error("unknown declaration: %r" % (data,))
379
380 # Internal -- helper to remove special character quoting
381 entitydefs = None
382 def unescape(self, s):
383 if '&' not in s:
384 return s
385 def replaceEntities(s):
386 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000387 try:
388 if s[0] == "#":
389 s = s[1:]
390 if s[0] in ['x','X']:
391 c = int(s[1:], 16)
392 else:
393 c = int(s)
394 return unichr(c)
395 except ValueError:
396 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000397 else:
398 # Cannot use name2codepoint directly, because HTMLParser supports apos,
399 # which is not part of HTML 4
400 import htmlentitydefs
401 if HTMLParser.entitydefs is None:
402 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
403 for k, v in htmlentitydefs.name2codepoint.iteritems():
404 entitydefs[k] = unichr(v)
405 try:
406 return self.entitydefs[s]
407 except KeyError:
408 return '&'+s+';'
409
410 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)