blob: 12c28b8339ffa25711dd59a6bc89c627a4fca4b9 [file] [log] [blame]
Fred Drake1d4601d2001-08-03 19:50:59 +00001"""A parser for HTML and XHTML."""
Guido van Rossum8846d712001-05-18 14:50:52 +00002
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 re
Ezio Melotti3861d8b2012-06-23 15:27:51 +020012import warnings
Ezio Melotti4a9ee262013-11-19 20:28:45 +020013import _markupbase
14
15from html import unescape
16
Guido van Rossum8846d712001-05-18 14:50:52 +000017
Ezio Melotti1698bab2013-05-01 16:09:34 +030018__all__ = ['HTMLParser']
19
Guido van Rossum8846d712001-05-18 14:50:52 +000020# Regular expressions used for parsing
21
22interesting_normal = re.compile('[&<]')
Fred Drake68eac2b2001-09-04 15:10:16 +000023incomplete = re.compile('&[a-zA-Z#]')
Guido van Rossum8846d712001-05-18 14:50:52 +000024
25entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
Fred Drake1d4601d2001-08-03 19:50:59 +000026charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
Guido van Rossum8846d712001-05-18 14:50:52 +000027
28starttagopen = re.compile('<[a-zA-Z]')
Guido van Rossum8846d712001-05-18 14:50:52 +000029piclose = re.compile('>')
Guido van Rossum8846d712001-05-18 14:50:52 +000030commentclose = re.compile(r'--\s*>')
Ezio Melotti29877e82012-02-21 09:25:00 +020031# Note:
32# 1) the strict attrfind isn't really strict, but we can't make it
33# correctly strict without breaking backward compatibility;
Ezio Melotti7165d8b2013-11-07 18:33:24 +020034# 2) if you change tagfind/attrfind remember to update locatestarttagend too;
35# 3) if you change tagfind/attrfind and/or locatestarttagend the parser will
Ezio Melotti29877e82012-02-21 09:25:00 +020036# explode, so don't do it.
Ezio Melotti7165d8b2013-11-07 18:33:24 +020037tagfind = re.compile('([a-zA-Z][-.a-zA-Z0-9:_]*)(?:\s|/(?!>))*')
38# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
39# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
40tagfind_tolerant = re.compile('([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
Guido van Rossum8846d712001-05-18 14:50:52 +000041attrfind = re.compile(
42 r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
Ezio Melotti2e3607c2011-04-07 22:03:31 +030043 r'(\'[^\']*\'|"[^"]*"|[^\s"\'=<>`]*))?')
R. David Murrayb579dba2010-12-03 04:06:39 +000044attrfind_tolerant = re.compile(
Ezio Melotti0780b6b2012-04-18 19:18:22 -060045 r'((?<=[\'"\s/])[^\s/>][^\s/=>]*)(\s*=+\s*'
Ezio Melotti29877e82012-02-21 09:25:00 +020046 r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*')
Guido van Rossum8846d712001-05-18 14:50:52 +000047locatestarttagend = re.compile(r"""
48 <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
49 (?:\s+ # whitespace before attribute name
50 (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
51 (?:\s*=\s* # value indicator
52 (?:'[^']*' # LITA-enclosed value
53 |\"[^\"]*\" # LIT-enclosed value
54 |[^'\">\s]+ # bare value
Georg Brandlcd3c26a2005-09-01 06:25:34 +000055 )
Guido van Rossum8846d712001-05-18 14:50:52 +000056 )?
57 )
58 )*
59 \s* # trailing whitespace
60""", re.VERBOSE)
R. David Murrayb579dba2010-12-03 04:06:39 +000061locatestarttagend_tolerant = re.compile(r"""
Ezio Melotti7165d8b2013-11-07 18:33:24 +020062 <[a-zA-Z][^\t\n\r\f />\x00]* # tag name
Ezio Melotti29877e82012-02-21 09:25:00 +020063 (?:[\s/]* # optional whitespace before attribute name
64 (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name
Ezio Melottic2fe5772011-11-14 18:53:33 +020065 (?:\s*=+\s* # value indicator
R. David Murrayb579dba2010-12-03 04:06:39 +000066 (?:'[^']*' # LITA-enclosed value
Ezio Melottic2fe5772011-11-14 18:53:33 +020067 |"[^"]*" # LIT-enclosed value
68 |(?!['"])[^>\s]* # bare value
R. David Murrayb579dba2010-12-03 04:06:39 +000069 )
70 (?:\s*,)* # possibly followed by a comma
Ezio Melotti29877e82012-02-21 09:25:00 +020071 )?(?:\s|/(?!>))*
Ezio Melottic2fe5772011-11-14 18:53:33 +020072 )*
73 )?
R. David Murrayb579dba2010-12-03 04:06:39 +000074 \s* # trailing whitespace
75""", re.VERBOSE)
Guido van Rossum8846d712001-05-18 14:50:52 +000076endendtag = re.compile('>')
Ezio Melotti7de56f62011-11-01 14:12:22 +020077# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
78# </ and the tag name, so maybe this should be fixed
Guido van Rossum8846d712001-05-18 14:50:52 +000079endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
80
Guido van Rossum8846d712001-05-18 14:50:52 +000081
82class HTMLParseError(Exception):
83 """Exception raised for all parse errors."""
84
85 def __init__(self, msg, position=(None, None)):
86 assert msg
87 self.msg = msg
88 self.lineno = position[0]
89 self.offset = position[1]
90
91 def __str__(self):
92 result = self.msg
93 if self.lineno is not None:
94 result = result + ", at line %d" % self.lineno
95 if self.offset is not None:
96 result = result + ", column %d" % (self.offset + 1)
97 return result
98
99
Ezio Melotti95401c52013-11-23 19:52:05 +0200100_default_sentinel = object()
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200101
Fred Drakecb5c80f2007-12-07 11:10:11 +0000102class HTMLParser(_markupbase.ParserBase):
Fred Drake1d4601d2001-08-03 19:50:59 +0000103 """Find tags and other markup and call handler functions.
104
105 Usage:
106 p = HTMLParser()
107 p.feed(data)
108 ...
109 p.close()
110
111 Start tags are handled by calling self.handle_starttag() or
112 self.handle_startendtag(); end tags by self.handle_endtag(). The
113 data between tags is passed from the parser to the derived class
114 by calling self.handle_data() with the data as argument (the data
Ezio Melotti95401c52013-11-23 19:52:05 +0200115 may be split up in arbitrary chunks). If convert_charrefs is
116 True the character references are converted automatically to the
117 corresponding Unicode character (and self.handle_data() is no
118 longer split in chunks), otherwise they are passed by calling
119 self.handle_entityref() or self.handle_charref() with the string
120 containing respectively the named or numeric reference as the
121 argument.
Fred Drake1d4601d2001-08-03 19:50:59 +0000122 """
Guido van Rossum8846d712001-05-18 14:50:52 +0000123
124 CDATA_CONTENT_ELEMENTS = ("script", "style")
125
Ezio Melotti95401c52013-11-23 19:52:05 +0200126 def __init__(self, strict=_default_sentinel, *,
127 convert_charrefs=_default_sentinel):
R. David Murrayb579dba2010-12-03 04:06:39 +0000128 """Initialize and reset this instance.
Guido van Rossum8846d712001-05-18 14:50:52 +0000129
Ezio Melotti95401c52013-11-23 19:52:05 +0200130 If convert_charrefs is True (default: False), all character references
131 are automatically converted to the corresponding Unicode characters.
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200132 If strict is set to False (the default) the parser will parse invalid
133 markup, otherwise it will raise an error. Note that the strict mode
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200134 and argument are deprecated.
R. David Murrayb579dba2010-12-03 04:06:39 +0000135 """
Ezio Melotti95401c52013-11-23 19:52:05 +0200136 if strict is not _default_sentinel:
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200137 warnings.warn("The strict argument and mode are deprecated.",
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200138 DeprecationWarning, stacklevel=2)
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200139 else:
140 strict = False # default
R. David Murrayb579dba2010-12-03 04:06:39 +0000141 self.strict = strict
Ezio Melotti95401c52013-11-23 19:52:05 +0200142 if convert_charrefs is _default_sentinel:
143 convert_charrefs = False # default
144 warnings.warn("The value of convert_charrefs will become True in "
145 "3.5. You are encouraged to set the value explicitly.",
146 DeprecationWarning, stacklevel=2)
147 self.convert_charrefs = convert_charrefs
Guido van Rossum8846d712001-05-18 14:50:52 +0000148 self.reset()
149
Guido van Rossum8846d712001-05-18 14:50:52 +0000150 def reset(self):
Fred Drake1d4601d2001-08-03 19:50:59 +0000151 """Reset this instance. Loses all unprocessed data."""
Guido van Rossum8846d712001-05-18 14:50:52 +0000152 self.rawdata = ''
Guido van Rossum8846d712001-05-18 14:50:52 +0000153 self.lasttag = '???'
Guido van Rossum8846d712001-05-18 14:50:52 +0000154 self.interesting = interesting_normal
Ezio Melotti7de56f62011-11-01 14:12:22 +0200155 self.cdata_elem = None
Fred Drakecb5c80f2007-12-07 11:10:11 +0000156 _markupbase.ParserBase.reset(self)
Guido van Rossum8846d712001-05-18 14:50:52 +0000157
Guido van Rossum8846d712001-05-18 14:50:52 +0000158 def feed(self, data):
Éric Araujo39f180b2011-05-04 15:55:47 +0200159 r"""Feed data to the parser.
Fred Drake1d4601d2001-08-03 19:50:59 +0000160
161 Call this as often as you want, with as little or as much text
162 as you want (may include '\n').
163 """
Guido van Rossum8846d712001-05-18 14:50:52 +0000164 self.rawdata = self.rawdata + data
165 self.goahead(0)
166
Guido van Rossum8846d712001-05-18 14:50:52 +0000167 def close(self):
Fred Drake1d4601d2001-08-03 19:50:59 +0000168 """Handle any buffered data."""
Guido van Rossum8846d712001-05-18 14:50:52 +0000169 self.goahead(1)
170
Fred Drakebfc8fea2001-09-24 20:10:28 +0000171 def error(self, message):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200172 warnings.warn("The 'error' method is deprecated.",
173 DeprecationWarning, stacklevel=2)
Fred Drakebfc8fea2001-09-24 20:10:28 +0000174 raise HTMLParseError(message, self.getpos())
Guido van Rossum8846d712001-05-18 14:50:52 +0000175
176 __starttag_text = None
177
Guido van Rossum8846d712001-05-18 14:50:52 +0000178 def get_starttag_text(self):
Fred Drake1d4601d2001-08-03 19:50:59 +0000179 """Return full source of start tag: '<...>'."""
Guido van Rossum8846d712001-05-18 14:50:52 +0000180 return self.__starttag_text
181
Ezio Melotti7de56f62011-11-01 14:12:22 +0200182 def set_cdata_mode(self, elem):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200183 self.cdata_elem = elem.lower()
Ezio Melotti15cb4892011-11-18 18:01:49 +0200184 self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
Guido van Rossum8846d712001-05-18 14:50:52 +0000185
186 def clear_cdata_mode(self):
187 self.interesting = interesting_normal
Ezio Melotti7de56f62011-11-01 14:12:22 +0200188 self.cdata_elem = None
Guido van Rossum8846d712001-05-18 14:50:52 +0000189
190 # Internal -- handle data as far as reasonable. May leave state
191 # and data to be processed by a subsequent call. If 'end' is
192 # true, force handling all data as if followed by EOF marker.
193 def goahead(self, end):
194 rawdata = self.rawdata
195 i = 0
196 n = len(rawdata)
197 while i < n:
Ezio Melotti95401c52013-11-23 19:52:05 +0200198 if self.convert_charrefs and not self.cdata_elem:
199 j = rawdata.find('<', i)
200 if j < 0:
201 if not end:
202 break # wait till we get all the text
203 j = n
Guido van Rossum8846d712001-05-18 14:50:52 +0000204 else:
Ezio Melotti95401c52013-11-23 19:52:05 +0200205 match = self.interesting.search(rawdata, i) # < or &
206 if match:
207 j = match.start()
208 else:
209 if self.cdata_elem:
210 break
211 j = n
212 if i < j:
213 if self.convert_charrefs and not self.cdata_elem:
214 self.handle_data(unescape(rawdata[i:j]))
215 else:
216 self.handle_data(rawdata[i:j])
Guido van Rossum8846d712001-05-18 14:50:52 +0000217 i = self.updatepos(i, j)
218 if i == n: break
Fred Drake248b0432001-12-03 17:09:50 +0000219 startswith = rawdata.startswith
220 if startswith('<', i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000221 if starttagopen.match(rawdata, i): # < + letter
222 k = self.parse_starttag(i)
Fred Drake248b0432001-12-03 17:09:50 +0000223 elif startswith("</", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000224 k = self.parse_endtag(i)
Fred Drake248b0432001-12-03 17:09:50 +0000225 elif startswith("<!--", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000226 k = self.parse_comment(i)
Fred Drake248b0432001-12-03 17:09:50 +0000227 elif startswith("<?", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000228 k = self.parse_pi(i)
Fred Drake248b0432001-12-03 17:09:50 +0000229 elif startswith("<!", i):
Ezio Melottifa3702d2012-02-10 10:45:44 +0200230 if self.strict:
231 k = self.parse_declaration(i)
232 else:
Ezio Melottif4ab4912012-02-13 15:50:37 +0200233 k = self.parse_html_declaration(i)
Fred Drake68eac2b2001-09-04 15:10:16 +0000234 elif (i + 1) < n:
Fred Drake029acfb2001-08-20 21:24:19 +0000235 self.handle_data("<")
236 k = i + 1
Fred Drake68eac2b2001-09-04 15:10:16 +0000237 else:
238 break
Guido van Rossum8846d712001-05-18 14:50:52 +0000239 if k < 0:
R. David Murrayb579dba2010-12-03 04:06:39 +0000240 if not end:
241 break
242 if self.strict:
Fred Drakebfc8fea2001-09-24 20:10:28 +0000243 self.error("EOF in middle of construct")
R. David Murrayb579dba2010-12-03 04:06:39 +0000244 k = rawdata.find('>', i + 1)
245 if k < 0:
246 k = rawdata.find('<', i + 1)
247 if k < 0:
248 k = i + 1
249 else:
250 k += 1
Ezio Melotti95401c52013-11-23 19:52:05 +0200251 if self.convert_charrefs and not self.cdata_elem:
252 self.handle_data(unescape(rawdata[i:k]))
253 else:
254 self.handle_data(rawdata[i:k])
Guido van Rossum8846d712001-05-18 14:50:52 +0000255 i = self.updatepos(i, k)
Fred Drake248b0432001-12-03 17:09:50 +0000256 elif startswith("&#", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000257 match = charref.match(rawdata, i)
258 if match:
Fred Drake1d4601d2001-08-03 19:50:59 +0000259 name = match.group()[2:-1]
Guido van Rossum8846d712001-05-18 14:50:52 +0000260 self.handle_charref(name)
261 k = match.end()
Fred Drake248b0432001-12-03 17:09:50 +0000262 if not startswith(';', k-1):
Fred Drake029acfb2001-08-20 21:24:19 +0000263 k = k - 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000264 i = self.updatepos(i, k)
265 continue
Fred Drake68eac2b2001-09-04 15:10:16 +0000266 else:
Victor Stinnere021f4b2010-05-24 21:46:25 +0000267 if ";" in rawdata[i:]: #bail by consuming &#
268 self.handle_data(rawdata[0:2])
269 i = self.updatepos(i, 2)
Fred Drake68eac2b2001-09-04 15:10:16 +0000270 break
Fred Drake248b0432001-12-03 17:09:50 +0000271 elif startswith('&', i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000272 match = entityref.match(rawdata, i)
273 if match:
274 name = match.group(1)
275 self.handle_entityref(name)
276 k = match.end()
Fred Drake248b0432001-12-03 17:09:50 +0000277 if not startswith(';', k-1):
Fred Drake029acfb2001-08-20 21:24:19 +0000278 k = k - 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000279 i = self.updatepos(i, k)
280 continue
Fred Drake029acfb2001-08-20 21:24:19 +0000281 match = incomplete.match(rawdata, i)
282 if match:
Fred Drake68eac2b2001-09-04 15:10:16 +0000283 # match.group() will contain at least 2 chars
Fred Drake248b0432001-12-03 17:09:50 +0000284 if end and match.group() == rawdata[i:]:
R. David Murrayb579dba2010-12-03 04:06:39 +0000285 if self.strict:
286 self.error("EOF in middle of entity or char ref")
287 else:
Ezio Melotti8e596a72013-05-01 16:18:25 +0300288 k = match.end()
R. David Murrayb579dba2010-12-03 04:06:39 +0000289 if k <= i:
290 k = n
291 i = self.updatepos(i, i + 1)
Fred Drake68eac2b2001-09-04 15:10:16 +0000292 # incomplete
293 break
294 elif (i + 1) < n:
295 # not the end of the buffer, and can't be confused
296 # with some other construct
297 self.handle_data("&")
298 i = self.updatepos(i, i + 1)
299 else:
300 break
Guido van Rossum8846d712001-05-18 14:50:52 +0000301 else:
302 assert 0, "interesting.search() lied"
303 # end while
Ezio Melotti15cb4892011-11-18 18:01:49 +0200304 if end and i < n and not self.cdata_elem:
Ezio Melotti95401c52013-11-23 19:52:05 +0200305 if self.convert_charrefs and not self.cdata_elem:
306 self.handle_data(unescape(rawdata[i:n]))
307 else:
308 self.handle_data(rawdata[i:n])
Guido van Rossum8846d712001-05-18 14:50:52 +0000309 i = self.updatepos(i, n)
310 self.rawdata = rawdata[i:]
311
Ezio Melottif4ab4912012-02-13 15:50:37 +0200312 # Internal -- parse html declarations, return length or -1 if not terminated
313 # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
314 # See also parse_declaration in _markupbase
315 def parse_html_declaration(self, i):
316 rawdata = self.rawdata
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200317 assert rawdata[i:i+2] == '<!', ('unexpected call to '
318 'parse_html_declaration()')
Ezio Melottif4ab4912012-02-13 15:50:37 +0200319 if rawdata[i:i+4] == '<!--':
Ezio Melottie31dded2012-02-13 20:20:00 +0200320 # this case is actually already handled in goahead()
Ezio Melottif4ab4912012-02-13 15:50:37 +0200321 return self.parse_comment(i)
322 elif rawdata[i:i+3] == '<![':
323 return self.parse_marked_section(i)
324 elif rawdata[i:i+9].lower() == '<!doctype':
325 # find the closing >
Ezio Melottie31dded2012-02-13 20:20:00 +0200326 gtpos = rawdata.find('>', i+9)
Ezio Melottif4ab4912012-02-13 15:50:37 +0200327 if gtpos == -1:
328 return -1
329 self.handle_decl(rawdata[i+2:gtpos])
330 return gtpos+1
331 else:
332 return self.parse_bogus_comment(i)
333
Ezio Melottifa3702d2012-02-10 10:45:44 +0200334 # Internal -- parse bogus comment, return length or -1 if not terminated
335 # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
336 def parse_bogus_comment(self, i, report=1):
337 rawdata = self.rawdata
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200338 assert rawdata[i:i+2] in ('<!', '</'), ('unexpected call to '
339 'parse_comment()')
Ezio Melottifa3702d2012-02-10 10:45:44 +0200340 pos = rawdata.find('>', i+2)
341 if pos == -1:
342 return -1
343 if report:
344 self.handle_comment(rawdata[i+2:pos])
345 return pos + 1
346
Guido van Rossum8846d712001-05-18 14:50:52 +0000347 # Internal -- parse processing instr, return end or -1 if not terminated
348 def parse_pi(self, i):
349 rawdata = self.rawdata
350 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
351 match = piclose.search(rawdata, i+2) # >
352 if not match:
353 return -1
354 j = match.start()
355 self.handle_pi(rawdata[i+2: j])
356 j = match.end()
357 return j
358
359 # Internal -- handle starttag, return end or -1 if not terminated
360 def parse_starttag(self, i):
361 self.__starttag_text = None
362 endpos = self.check_for_whole_start_tag(i)
363 if endpos < 0:
364 return endpos
365 rawdata = self.rawdata
366 self.__starttag_text = rawdata[i:endpos]
367
368 # Now parse the data between i+1 and j into a tag and attrs
369 attrs = []
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200370 if self.strict:
371 match = tagfind.match(rawdata, i+1)
372 else:
373 match = tagfind_tolerant.match(rawdata, i+1)
Guido van Rossum8846d712001-05-18 14:50:52 +0000374 assert match, 'unexpected call to parse_starttag()'
375 k = match.end()
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600376 self.lasttag = tag = match.group(1).lower()
Guido van Rossum8846d712001-05-18 14:50:52 +0000377 while k < endpos:
R. David Murrayb579dba2010-12-03 04:06:39 +0000378 if self.strict:
379 m = attrfind.match(rawdata, k)
380 else:
Ezio Melottif50ffa92011-10-28 13:21:09 +0300381 m = attrfind_tolerant.match(rawdata, k)
Guido van Rossum8846d712001-05-18 14:50:52 +0000382 if not m:
383 break
384 attrname, rest, attrvalue = m.group(1, 2, 3)
385 if not rest:
386 attrvalue = None
387 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
388 attrvalue[:1] == '"' == attrvalue[-1:]:
389 attrvalue = attrvalue[1:-1]
Ezio Melottic2fe5772011-11-14 18:53:33 +0200390 if attrvalue:
Ezio Melotti4a9ee262013-11-19 20:28:45 +0200391 attrvalue = unescape(attrvalue)
Fred Drake248b0432001-12-03 17:09:50 +0000392 attrs.append((attrname.lower(), attrvalue))
Guido van Rossum8846d712001-05-18 14:50:52 +0000393 k = m.end()
394
Fred Drake248b0432001-12-03 17:09:50 +0000395 end = rawdata[k:endpos].strip()
Guido van Rossum8846d712001-05-18 14:50:52 +0000396 if end not in (">", "/>"):
397 lineno, offset = self.getpos()
398 if "\n" in self.__starttag_text:
Fred Drake248b0432001-12-03 17:09:50 +0000399 lineno = lineno + self.__starttag_text.count("\n")
Guido van Rossum8846d712001-05-18 14:50:52 +0000400 offset = len(self.__starttag_text) \
Fred Drake248b0432001-12-03 17:09:50 +0000401 - self.__starttag_text.rfind("\n")
Guido van Rossum8846d712001-05-18 14:50:52 +0000402 else:
403 offset = offset + len(self.__starttag_text)
R. David Murrayb579dba2010-12-03 04:06:39 +0000404 if self.strict:
405 self.error("junk characters in start tag: %r"
406 % (rawdata[k:endpos][:20],))
407 self.handle_data(rawdata[i:endpos])
408 return endpos
Fred Drake248b0432001-12-03 17:09:50 +0000409 if end.endswith('/>'):
Guido van Rossum8846d712001-05-18 14:50:52 +0000410 # XHTML-style empty tag: <span attr="value" />
411 self.handle_startendtag(tag, attrs)
412 else:
413 self.handle_starttag(tag, attrs)
414 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7de56f62011-11-01 14:12:22 +0200415 self.set_cdata_mode(tag)
Guido van Rossum8846d712001-05-18 14:50:52 +0000416 return endpos
417
418 # Internal -- check to see if we have a complete starttag; return end
419 # or -1 if incomplete.
420 def check_for_whole_start_tag(self, i):
421 rawdata = self.rawdata
R. David Murrayb579dba2010-12-03 04:06:39 +0000422 if self.strict:
423 m = locatestarttagend.match(rawdata, i)
424 else:
425 m = locatestarttagend_tolerant.match(rawdata, i)
Guido van Rossum8846d712001-05-18 14:50:52 +0000426 if m:
427 j = m.end()
428 next = rawdata[j:j+1]
429 if next == ">":
430 return j + 1
431 if next == "/":
Fred Drake248b0432001-12-03 17:09:50 +0000432 if rawdata.startswith("/>", j):
Guido van Rossum8846d712001-05-18 14:50:52 +0000433 return j + 2
Fred Drake248b0432001-12-03 17:09:50 +0000434 if rawdata.startswith("/", j):
Guido van Rossum8846d712001-05-18 14:50:52 +0000435 # buffer boundary
436 return -1
437 # else bogus input
R. David Murrayb579dba2010-12-03 04:06:39 +0000438 if self.strict:
439 self.updatepos(i, j + 1)
440 self.error("malformed empty start tag")
441 if j > i:
442 return j
443 else:
444 return i + 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000445 if next == "":
446 # end of input
447 return -1
448 if next in ("abcdefghijklmnopqrstuvwxyz=/"
449 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
450 # end of input in or before attribute value, or we have the
451 # '/' from a '/>' ending
452 return -1
R. David Murrayb579dba2010-12-03 04:06:39 +0000453 if self.strict:
454 self.updatepos(i, j)
455 self.error("malformed start tag")
456 if j > i:
457 return j
458 else:
459 return i + 1
Fred Drakebfc8fea2001-09-24 20:10:28 +0000460 raise AssertionError("we should not get here!")
Guido van Rossum8846d712001-05-18 14:50:52 +0000461
462 # Internal -- parse endtag, return end or -1 if incomplete
463 def parse_endtag(self, i):
464 rawdata = self.rawdata
465 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
466 match = endendtag.search(rawdata, i+1) # >
467 if not match:
468 return -1
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200469 gtpos = match.end()
Guido van Rossum8846d712001-05-18 14:50:52 +0000470 match = endtagfind.match(rawdata, i) # </ + tag + >
471 if not match:
Ezio Melotti7de56f62011-11-01 14:12:22 +0200472 if self.cdata_elem is not None:
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200473 self.handle_data(rawdata[i:gtpos])
474 return gtpos
R. David Murrayb579dba2010-12-03 04:06:39 +0000475 if self.strict:
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200476 self.error("bad end tag: %r" % (rawdata[i:gtpos],))
477 # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
478 namematch = tagfind_tolerant.match(rawdata, i+2)
479 if not namematch:
480 # w3.org/TR/html5/tokenization.html#end-tag-open-state
481 if rawdata[i:i+3] == '</>':
482 return i+3
483 else:
484 return self.parse_bogus_comment(i)
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200485 tagname = namematch.group(1).lower()
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200486 # consume and ignore other stuff between the name and the >
487 # Note: this is not 100% correct, since we might have things like
488 # </tag attr=">">, but looking for > after tha name should cover
489 # most of the cases and is much simpler
490 gtpos = rawdata.find('>', namematch.end())
491 self.handle_endtag(tagname)
492 return gtpos+1
Ezio Melotti7de56f62011-11-01 14:12:22 +0200493
494 elem = match.group(1).lower() # script or style
495 if self.cdata_elem is not None:
496 if elem != self.cdata_elem:
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200497 self.handle_data(rawdata[i:gtpos])
498 return gtpos
Ezio Melotti7de56f62011-11-01 14:12:22 +0200499
500 self.handle_endtag(elem.lower())
Fred Drake30d59ba2002-05-14 15:50:11 +0000501 self.clear_cdata_mode()
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200502 return gtpos
Guido van Rossum8846d712001-05-18 14:50:52 +0000503
504 # Overridable -- finish processing of start+end tag: <tag.../>
505 def handle_startendtag(self, tag, attrs):
506 self.handle_starttag(tag, attrs)
507 self.handle_endtag(tag)
508
509 # Overridable -- handle start tag
510 def handle_starttag(self, tag, attrs):
511 pass
512
513 # Overridable -- handle end tag
514 def handle_endtag(self, tag):
515 pass
516
517 # Overridable -- handle character reference
518 def handle_charref(self, name):
519 pass
520
521 # Overridable -- handle entity reference
522 def handle_entityref(self, name):
523 pass
524
525 # Overridable -- handle data
526 def handle_data(self, data):
527 pass
528
529 # Overridable -- handle comment
530 def handle_comment(self, data):
531 pass
532
533 # Overridable -- handle declaration
534 def handle_decl(self, decl):
535 pass
536
537 # Overridable -- handle processing instruction
538 def handle_pi(self, data):
539 pass
540
Fred Drakebfc8fea2001-09-24 20:10:28 +0000541 def unknown_decl(self, data):
R. David Murrayb579dba2010-12-03 04:06:39 +0000542 if self.strict:
543 self.error("unknown declaration: %r" % (data,))
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200544
545 # Internal -- helper to remove special character quoting
546 def unescape(self, s):
547 warnings.warn('The unescape method is deprecated and will be removed '
548 'in 3.5, use html.unescape() instead.',
549 DeprecationWarning, stacklevel=2)
550 return unescape(s)