blob: 94ebc7f8dc44aaef37af607dea8f9dd04d039cda [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('[&<]')
17interesting_cdata = re.compile(r'<(/|\Z)')
18incomplete = re.compile('&[a-zA-Z#]')
19
20entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
21charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
22
23starttagopen = re.compile('<[a-zA-Z]')
24piclose = re.compile('>')
25commentclose = re.compile(r'--\s*>')
26tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
27attrfind = re.compile(
28 r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
Ezio Melotti9f1ffb22011-04-05 20:40:52 +030029 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
34 (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
35 (?:\s*=\s* # value indicator
36 (?:'[^']*' # LITA-enclosed value
37 |\"[^\"]*\" # LIT-enclosed value
38 |[^'\">\s]+ # bare value
39 )
40 )?
41 )
42 )*
43 \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):
Fred Draked995e112008-05-20 06:08:38 +0000127 self.interesting = interesting_cdata
Ezio Melotti7e82b272011-11-01 14:09:56 +0200128 self.cdata_elem = elem.lower()
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:
146 j = n
147 if i < j: self.handle_data(rawdata[i:j])
148 i = self.updatepos(i, j)
149 if i == n: break
150 startswith = rawdata.startswith
151 if startswith('<', i):
152 if starttagopen.match(rawdata, i): # < + letter
153 k = self.parse_starttag(i)
154 elif startswith("</", i):
155 k = self.parse_endtag(i)
156 elif startswith("<!--", i):
157 k = self.parse_comment(i)
158 elif startswith("<?", i):
159 k = self.parse_pi(i)
160 elif startswith("<!", i):
161 k = self.parse_declaration(i)
162 elif (i + 1) < n:
163 self.handle_data("<")
164 k = i + 1
165 else:
166 break
167 if k < 0:
168 if end:
169 self.error("EOF in middle of construct")
170 break
171 i = self.updatepos(i, k)
172 elif startswith("&#", i):
173 match = charref.match(rawdata, i)
174 if match:
175 name = match.group()[2:-1]
176 self.handle_charref(name)
177 k = match.end()
178 if not startswith(';', k-1):
179 k = k - 1
180 i = self.updatepos(i, k)
181 continue
182 else:
Victor Stinner554a3b82010-05-24 21:33:24 +0000183 if ";" in rawdata[i:]: #bail by consuming &#
184 self.handle_data(rawdata[0:2])
185 i = self.updatepos(i, 2)
Fred Draked995e112008-05-20 06:08:38 +0000186 break
187 elif startswith('&', i):
188 match = entityref.match(rawdata, i)
189 if match:
190 name = match.group(1)
191 self.handle_entityref(name)
192 k = match.end()
193 if not startswith(';', k-1):
194 k = k - 1
195 i = self.updatepos(i, k)
196 continue
197 match = incomplete.match(rawdata, i)
198 if match:
199 # match.group() will contain at least 2 chars
200 if end and match.group() == rawdata[i:]:
201 self.error("EOF in middle of entity or char ref")
202 # incomplete
203 break
204 elif (i + 1) < n:
205 # not the end of the buffer, and can't be confused
206 # with some other construct
207 self.handle_data("&")
208 i = self.updatepos(i, i + 1)
209 else:
210 break
211 else:
212 assert 0, "interesting.search() lied"
213 # end while
214 if end and i < n:
215 self.handle_data(rawdata[i:n])
216 i = self.updatepos(i, n)
217 self.rawdata = rawdata[i:]
218
219 # Internal -- parse processing instr, return end or -1 if not terminated
220 def parse_pi(self, i):
221 rawdata = self.rawdata
222 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
223 match = piclose.search(rawdata, i+2) # >
224 if not match:
225 return -1
226 j = match.start()
227 self.handle_pi(rawdata[i+2: j])
228 j = match.end()
229 return j
230
231 # Internal -- handle starttag, return end or -1 if not terminated
232 def parse_starttag(self, i):
233 self.__starttag_text = None
234 endpos = self.check_for_whole_start_tag(i)
235 if endpos < 0:
236 return endpos
237 rawdata = self.rawdata
238 self.__starttag_text = rawdata[i:endpos]
239
240 # Now parse the data between i+1 and j into a tag and attrs
241 attrs = []
242 match = tagfind.match(rawdata, i+1)
243 assert match, 'unexpected call to parse_starttag()'
244 k = match.end()
245 self.lasttag = tag = rawdata[i+1:k].lower()
246
247 while k < endpos:
248 m = attrfind.match(rawdata, k)
249 if not m:
250 break
251 attrname, rest, attrvalue = m.group(1, 2, 3)
252 if not rest:
253 attrvalue = None
254 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
255 attrvalue[:1] == '"' == attrvalue[-1:]:
256 attrvalue = attrvalue[1:-1]
257 attrvalue = self.unescape(attrvalue)
258 attrs.append((attrname.lower(), attrvalue))
259 k = m.end()
260
261 end = rawdata[k:endpos].strip()
262 if end not in (">", "/>"):
263 lineno, offset = self.getpos()
264 if "\n" in self.__starttag_text:
265 lineno = lineno + self.__starttag_text.count("\n")
266 offset = len(self.__starttag_text) \
267 - self.__starttag_text.rfind("\n")
268 else:
269 offset = offset + len(self.__starttag_text)
270 self.error("junk characters in start tag: %r"
271 % (rawdata[k:endpos][:20],))
272 if end.endswith('/>'):
273 # XHTML-style empty tag: <span attr="value" />
274 self.handle_startendtag(tag, attrs)
275 else:
276 self.handle_starttag(tag, attrs)
277 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200278 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000279 return endpos
280
281 # Internal -- check to see if we have a complete starttag; return end
282 # or -1 if incomplete.
283 def check_for_whole_start_tag(self, i):
284 rawdata = self.rawdata
285 m = locatestarttagend.match(rawdata, i)
286 if m:
287 j = m.end()
288 next = rawdata[j:j+1]
289 if next == ">":
290 return j + 1
291 if next == "/":
292 if rawdata.startswith("/>", j):
293 return j + 2
294 if rawdata.startswith("/", j):
295 # buffer boundary
296 return -1
297 # else bogus input
298 self.updatepos(i, j + 1)
299 self.error("malformed empty start tag")
300 if next == "":
301 # end of input
302 return -1
303 if next in ("abcdefghijklmnopqrstuvwxyz=/"
304 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
305 # end of input in or before attribute value, or we have the
306 # '/' from a '/>' ending
307 return -1
308 self.updatepos(i, j)
309 self.error("malformed start tag")
310 raise AssertionError("we should not get here!")
311
312 # Internal -- parse endtag, return end or -1 if incomplete
313 def parse_endtag(self, i):
314 rawdata = self.rawdata
315 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
316 match = endendtag.search(rawdata, i+1) # >
317 if not match:
318 return -1
319 j = match.end()
320 match = endtagfind.match(rawdata, i) # </ + tag + >
321 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200322 if self.cdata_elem is not None:
323 self.handle_data(rawdata[i:j])
324 return j
Fred Draked995e112008-05-20 06:08:38 +0000325 self.error("bad end tag: %r" % (rawdata[i:j],))
Ezio Melotti7e82b272011-11-01 14:09:56 +0200326
327 elem = match.group(1).lower() # script or style
328 if self.cdata_elem is not None:
329 if elem != self.cdata_elem:
330 self.handle_data(rawdata[i:j])
331 return j
332
333 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000334 self.clear_cdata_mode()
335 return j
336
337 # Overridable -- finish processing of start+end tag: <tag.../>
338 def handle_startendtag(self, tag, attrs):
339 self.handle_starttag(tag, attrs)
340 self.handle_endtag(tag)
341
342 # Overridable -- handle start tag
343 def handle_starttag(self, tag, attrs):
344 pass
345
346 # Overridable -- handle end tag
347 def handle_endtag(self, tag):
348 pass
349
350 # Overridable -- handle character reference
351 def handle_charref(self, name):
352 pass
353
354 # Overridable -- handle entity reference
355 def handle_entityref(self, name):
356 pass
357
358 # Overridable -- handle data
359 def handle_data(self, data):
360 pass
361
362 # Overridable -- handle comment
363 def handle_comment(self, data):
364 pass
365
366 # Overridable -- handle declaration
367 def handle_decl(self, decl):
368 pass
369
370 # Overridable -- handle processing instruction
371 def handle_pi(self, data):
372 pass
373
374 def unknown_decl(self, data):
375 self.error("unknown declaration: %r" % (data,))
376
377 # Internal -- helper to remove special character quoting
378 entitydefs = None
379 def unescape(self, s):
380 if '&' not in s:
381 return s
382 def replaceEntities(s):
383 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000384 try:
385 if s[0] == "#":
386 s = s[1:]
387 if s[0] in ['x','X']:
388 c = int(s[1:], 16)
389 else:
390 c = int(s)
391 return unichr(c)
392 except ValueError:
393 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000394 else:
395 # Cannot use name2codepoint directly, because HTMLParser supports apos,
396 # which is not part of HTML 4
397 import htmlentitydefs
398 if HTMLParser.entitydefs is None:
399 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
400 for k, v in htmlentitydefs.name2codepoint.iteritems():
401 entitydefs[k] = unichr(v)
402 try:
403 return self.entitydefs[s]
404 except KeyError:
405 return '&'+s+';'
406
407 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)