blob: cd353f8ca037476ec570092b491e8932b07cc478 [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:_]*')
Ezio Melotti0f1571c2011-11-14 18:04:05 +020027
Fred Draked995e112008-05-20 06:08:38 +000028attrfind = re.compile(
Ezio Melotti0f1571c2011-11-14 18:04:05 +020029 r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
30 r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
Fred Draked995e112008-05-20 06:08:38 +000031
32locatestarttagend = re.compile(r"""
33 <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
34 (?:\s+ # whitespace before attribute name
Ezio Melotti0f1571c2011-11-14 18:04:05 +020035 (?:(?<=['"\s])[^\s/>][^\s/=>]* # attribute name
36 (?:\s*=+\s* # value indicator
Fred Draked995e112008-05-20 06:08:38 +000037 (?:'[^']*' # LITA-enclosed value
Ezio Melotti0f1571c2011-11-14 18:04:05 +020038 |"[^"]*" # LIT-enclosed value
39 |(?!['"])[^>\s]* # bare value
Fred Draked995e112008-05-20 06:08:38 +000040 )
Ezio Melotti0f1571c2011-11-14 18:04:05 +020041 )?\s*
42 )*
43 )?
Fred Draked995e112008-05-20 06:08:38 +000044 \s* # trailing whitespace
45""", re.VERBOSE)
46endendtag = re.compile('>')
Ezio Melotti7e82b272011-11-01 14:09:56 +020047# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
48# </ and the tag name, so maybe this should be fixed
Fred Draked995e112008-05-20 06:08:38 +000049endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
50
51
52class HTMLParseError(Exception):
53 """Exception raised for all parse errors."""
54
55 def __init__(self, msg, position=(None, None)):
56 assert msg
57 self.msg = msg
58 self.lineno = position[0]
59 self.offset = position[1]
60
61 def __str__(self):
62 result = self.msg
63 if self.lineno is not None:
64 result = result + ", at line %d" % self.lineno
65 if self.offset is not None:
66 result = result + ", column %d" % (self.offset + 1)
67 return result
68
69
70class HTMLParser(markupbase.ParserBase):
71 """Find tags and other markup and call handler functions.
72
73 Usage:
74 p = HTMLParser()
75 p.feed(data)
76 ...
77 p.close()
78
79 Start tags are handled by calling self.handle_starttag() or
80 self.handle_startendtag(); end tags by self.handle_endtag(). The
81 data between tags is passed from the parser to the derived class
82 by calling self.handle_data() with the data as argument (the data
83 may be split up in arbitrary chunks). Entity references are
84 passed by calling self.handle_entityref() with the entity
85 reference as the argument. Numeric character references are
86 passed to self.handle_charref() with the string containing the
87 reference as the argument.
88 """
89
90 CDATA_CONTENT_ELEMENTS = ("script", "style")
91
92
93 def __init__(self):
94 """Initialize and reset this instance."""
95 self.reset()
96
97 def reset(self):
98 """Reset this instance. Loses all unprocessed data."""
99 self.rawdata = ''
100 self.lasttag = '???'
101 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200102 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000103 markupbase.ParserBase.reset(self)
104
105 def feed(self, data):
Éric Araujo31890bc2011-05-25 18:11:43 +0200106 r"""Feed data to the parser.
Fred Draked995e112008-05-20 06:08:38 +0000107
108 Call this as often as you want, with as little or as much text
109 as you want (may include '\n').
110 """
111 self.rawdata = self.rawdata + data
112 self.goahead(0)
113
114 def close(self):
115 """Handle any buffered data."""
116 self.goahead(1)
117
118 def error(self, message):
119 raise HTMLParseError(message, self.getpos())
120
121 __starttag_text = None
122
123 def get_starttag_text(self):
124 """Return full source of start tag: '<...>'."""
125 return self.__starttag_text
126
Ezio Melotti7e82b272011-11-01 14:09:56 +0200127 def set_cdata_mode(self, elem):
Fred Draked995e112008-05-20 06:08:38 +0000128 self.interesting = interesting_cdata
Ezio Melotti7e82b272011-11-01 14:09:56 +0200129 self.cdata_elem = elem.lower()
Fred Draked995e112008-05-20 06:08:38 +0000130
131 def clear_cdata_mode(self):
132 self.interesting = interesting_normal
Ezio Melotti7e82b272011-11-01 14:09:56 +0200133 self.cdata_elem = None
Fred Draked995e112008-05-20 06:08:38 +0000134
135 # Internal -- handle data as far as reasonable. May leave state
136 # and data to be processed by a subsequent call. If 'end' is
137 # true, force handling all data as if followed by EOF marker.
138 def goahead(self, end):
139 rawdata = self.rawdata
140 i = 0
141 n = len(rawdata)
142 while i < n:
143 match = self.interesting.search(rawdata, i) # < or &
144 if match:
145 j = match.start()
146 else:
147 j = n
148 if i < j: self.handle_data(rawdata[i:j])
149 i = self.updatepos(i, j)
150 if i == n: break
151 startswith = rawdata.startswith
152 if startswith('<', i):
153 if starttagopen.match(rawdata, i): # < + letter
154 k = self.parse_starttag(i)
155 elif startswith("</", i):
156 k = self.parse_endtag(i)
157 elif startswith("<!--", i):
158 k = self.parse_comment(i)
159 elif startswith("<?", i):
160 k = self.parse_pi(i)
161 elif startswith("<!", i):
162 k = self.parse_declaration(i)
163 elif (i + 1) < n:
164 self.handle_data("<")
165 k = i + 1
166 else:
167 break
168 if k < 0:
169 if end:
170 self.error("EOF in middle of construct")
171 break
172 i = self.updatepos(i, k)
173 elif startswith("&#", i):
174 match = charref.match(rawdata, i)
175 if match:
176 name = match.group()[2:-1]
177 self.handle_charref(name)
178 k = match.end()
179 if not startswith(';', k-1):
180 k = k - 1
181 i = self.updatepos(i, k)
182 continue
183 else:
Victor Stinner554a3b82010-05-24 21:33:24 +0000184 if ";" in rawdata[i:]: #bail by consuming &#
185 self.handle_data(rawdata[0:2])
186 i = self.updatepos(i, 2)
Fred Draked995e112008-05-20 06:08:38 +0000187 break
188 elif startswith('&', i):
189 match = entityref.match(rawdata, i)
190 if match:
191 name = match.group(1)
192 self.handle_entityref(name)
193 k = match.end()
194 if not startswith(';', k-1):
195 k = k - 1
196 i = self.updatepos(i, k)
197 continue
198 match = incomplete.match(rawdata, i)
199 if match:
200 # match.group() will contain at least 2 chars
201 if end and match.group() == rawdata[i:]:
202 self.error("EOF in middle of entity or char ref")
203 # incomplete
204 break
205 elif (i + 1) < n:
206 # not the end of the buffer, and can't be confused
207 # with some other construct
208 self.handle_data("&")
209 i = self.updatepos(i, i + 1)
210 else:
211 break
212 else:
213 assert 0, "interesting.search() lied"
214 # end while
215 if end and i < n:
216 self.handle_data(rawdata[i:n])
217 i = self.updatepos(i, n)
218 self.rawdata = rawdata[i:]
219
220 # Internal -- parse processing instr, return end or -1 if not terminated
221 def parse_pi(self, i):
222 rawdata = self.rawdata
223 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
224 match = piclose.search(rawdata, i+2) # >
225 if not match:
226 return -1
227 j = match.start()
228 self.handle_pi(rawdata[i+2: j])
229 j = match.end()
230 return j
231
232 # Internal -- handle starttag, return end or -1 if not terminated
233 def parse_starttag(self, i):
234 self.__starttag_text = None
235 endpos = self.check_for_whole_start_tag(i)
236 if endpos < 0:
237 return endpos
238 rawdata = self.rawdata
239 self.__starttag_text = rawdata[i:endpos]
240
241 # Now parse the data between i+1 and j into a tag and attrs
242 attrs = []
243 match = tagfind.match(rawdata, i+1)
244 assert match, 'unexpected call to parse_starttag()'
245 k = match.end()
246 self.lasttag = tag = rawdata[i+1:k].lower()
247
248 while k < endpos:
249 m = attrfind.match(rawdata, k)
250 if not m:
251 break
252 attrname, rest, attrvalue = m.group(1, 2, 3)
253 if not rest:
254 attrvalue = None
255 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
256 attrvalue[:1] == '"' == attrvalue[-1:]:
257 attrvalue = attrvalue[1:-1]
Ezio Melotti0f1571c2011-11-14 18:04:05 +0200258 if attrvalue:
Fred Draked995e112008-05-20 06:08:38 +0000259 attrvalue = self.unescape(attrvalue)
260 attrs.append((attrname.lower(), attrvalue))
261 k = m.end()
262
263 end = rawdata[k:endpos].strip()
264 if end not in (">", "/>"):
265 lineno, offset = self.getpos()
266 if "\n" in self.__starttag_text:
267 lineno = lineno + self.__starttag_text.count("\n")
268 offset = len(self.__starttag_text) \
269 - self.__starttag_text.rfind("\n")
270 else:
271 offset = offset + len(self.__starttag_text)
272 self.error("junk characters in start tag: %r"
273 % (rawdata[k:endpos][:20],))
274 if end.endswith('/>'):
275 # XHTML-style empty tag: <span attr="value" />
276 self.handle_startendtag(tag, attrs)
277 else:
278 self.handle_starttag(tag, attrs)
279 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200280 self.set_cdata_mode(tag)
Fred Draked995e112008-05-20 06:08:38 +0000281 return endpos
282
283 # Internal -- check to see if we have a complete starttag; return end
284 # or -1 if incomplete.
285 def check_for_whole_start_tag(self, i):
286 rawdata = self.rawdata
287 m = locatestarttagend.match(rawdata, i)
288 if m:
289 j = m.end()
290 next = rawdata[j:j+1]
291 if next == ">":
292 return j + 1
293 if next == "/":
294 if rawdata.startswith("/>", j):
295 return j + 2
296 if rawdata.startswith("/", j):
297 # buffer boundary
298 return -1
299 # else bogus input
300 self.updatepos(i, j + 1)
301 self.error("malformed empty start tag")
302 if next == "":
303 # end of input
304 return -1
305 if next in ("abcdefghijklmnopqrstuvwxyz=/"
306 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
307 # end of input in or before attribute value, or we have the
308 # '/' from a '/>' ending
309 return -1
310 self.updatepos(i, j)
311 self.error("malformed start tag")
312 raise AssertionError("we should not get here!")
313
314 # Internal -- parse endtag, return end or -1 if incomplete
315 def parse_endtag(self, i):
316 rawdata = self.rawdata
317 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
318 match = endendtag.search(rawdata, i+1) # >
319 if not match:
320 return -1
321 j = match.end()
322 match = endtagfind.match(rawdata, i) # </ + tag + >
323 if not match:
Ezio Melotti7e82b272011-11-01 14:09:56 +0200324 if self.cdata_elem is not None:
325 self.handle_data(rawdata[i:j])
326 return j
Fred Draked995e112008-05-20 06:08:38 +0000327 self.error("bad end tag: %r" % (rawdata[i:j],))
Ezio Melotti7e82b272011-11-01 14:09:56 +0200328
329 elem = match.group(1).lower() # script or style
330 if self.cdata_elem is not None:
331 if elem != self.cdata_elem:
332 self.handle_data(rawdata[i:j])
333 return j
334
335 self.handle_endtag(elem)
Fred Draked995e112008-05-20 06:08:38 +0000336 self.clear_cdata_mode()
337 return j
338
339 # Overridable -- finish processing of start+end tag: <tag.../>
340 def handle_startendtag(self, tag, attrs):
341 self.handle_starttag(tag, attrs)
342 self.handle_endtag(tag)
343
344 # Overridable -- handle start tag
345 def handle_starttag(self, tag, attrs):
346 pass
347
348 # Overridable -- handle end tag
349 def handle_endtag(self, tag):
350 pass
351
352 # Overridable -- handle character reference
353 def handle_charref(self, name):
354 pass
355
356 # Overridable -- handle entity reference
357 def handle_entityref(self, name):
358 pass
359
360 # Overridable -- handle data
361 def handle_data(self, data):
362 pass
363
364 # Overridable -- handle comment
365 def handle_comment(self, data):
366 pass
367
368 # Overridable -- handle declaration
369 def handle_decl(self, decl):
370 pass
371
372 # Overridable -- handle processing instruction
373 def handle_pi(self, data):
374 pass
375
376 def unknown_decl(self, data):
377 self.error("unknown declaration: %r" % (data,))
378
379 # Internal -- helper to remove special character quoting
380 entitydefs = None
381 def unescape(self, s):
382 if '&' not in s:
383 return s
384 def replaceEntities(s):
385 s = s.groups()[0]
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000386 try:
387 if s[0] == "#":
388 s = s[1:]
389 if s[0] in ['x','X']:
390 c = int(s[1:], 16)
391 else:
392 c = int(s)
393 return unichr(c)
394 except ValueError:
395 return '&#'+s+';'
Fred Draked995e112008-05-20 06:08:38 +0000396 else:
397 # Cannot use name2codepoint directly, because HTMLParser supports apos,
398 # which is not part of HTML 4
399 import htmlentitydefs
400 if HTMLParser.entitydefs is None:
401 entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
402 for k, v in htmlentitydefs.name2codepoint.iteritems():
403 entitydefs[k] = unichr(v)
404 try:
405 return self.entitydefs[s]
406 except KeyError:
407 return '&'+s+';'
408
409 return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)