blob: 43e6411b735c2177d5cde5cdbde018720c6618c5 [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:
Ezio Melotti73a43592014-08-02 14:10:30 +030032# 1) if you change tagfind/attrfind remember to update locatestarttagend too;
33# 2) if you change tagfind/attrfind and/or locatestarttagend the parser will
Ezio Melotti29877e82012-02-21 09:25:00 +020034# explode, so don't do it.
Ezio Melotti7165d8b2013-11-07 18:33:24 +020035# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
36# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
37tagfind_tolerant = re.compile('([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
R. David Murrayb579dba2010-12-03 04:06:39 +000038attrfind_tolerant = re.compile(
Ezio Melotti0780b6b2012-04-18 19:18:22 -060039 r'((?<=[\'"\s/])[^\s/>][^\s/=>]*)(\s*=+\s*'
Ezio Melotti29877e82012-02-21 09:25:00 +020040 r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*')
R. David Murrayb579dba2010-12-03 04:06:39 +000041locatestarttagend_tolerant = re.compile(r"""
Ezio Melotti7165d8b2013-11-07 18:33:24 +020042 <[a-zA-Z][^\t\n\r\f />\x00]* # tag name
Ezio Melotti29877e82012-02-21 09:25:00 +020043 (?:[\s/]* # optional whitespace before attribute name
44 (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name
Ezio Melottic2fe5772011-11-14 18:53:33 +020045 (?:\s*=+\s* # value indicator
R. David Murrayb579dba2010-12-03 04:06:39 +000046 (?:'[^']*' # LITA-enclosed value
Ezio Melottic2fe5772011-11-14 18:53:33 +020047 |"[^"]*" # LIT-enclosed value
48 |(?!['"])[^>\s]* # bare value
R. David Murrayb579dba2010-12-03 04:06:39 +000049 )
50 (?:\s*,)* # possibly followed by a comma
Ezio Melotti29877e82012-02-21 09:25:00 +020051 )?(?:\s|/(?!>))*
Ezio Melottic2fe5772011-11-14 18:53:33 +020052 )*
53 )?
R. David Murrayb579dba2010-12-03 04:06:39 +000054 \s* # trailing whitespace
55""", re.VERBOSE)
Guido van Rossum8846d712001-05-18 14:50:52 +000056endendtag = re.compile('>')
Ezio Melotti7de56f62011-11-01 14:12:22 +020057# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
58# </ and the tag name, so maybe this should be fixed
Guido van Rossum8846d712001-05-18 14:50:52 +000059endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
60
Guido van Rossum8846d712001-05-18 14:50:52 +000061
Ezio Melotti88ebfb12013-11-02 17:08:24 +020062
Fred Drakecb5c80f2007-12-07 11:10:11 +000063class HTMLParser(_markupbase.ParserBase):
Fred Drake1d4601d2001-08-03 19:50:59 +000064 """Find tags and other markup and call handler functions.
65
66 Usage:
67 p = HTMLParser()
68 p.feed(data)
69 ...
70 p.close()
71
72 Start tags are handled by calling self.handle_starttag() or
73 self.handle_startendtag(); end tags by self.handle_endtag(). The
74 data between tags is passed from the parser to the derived class
75 by calling self.handle_data() with the data as argument (the data
Ezio Melotti95401c52013-11-23 19:52:05 +020076 may be split up in arbitrary chunks). If convert_charrefs is
77 True the character references are converted automatically to the
78 corresponding Unicode character (and self.handle_data() is no
79 longer split in chunks), otherwise they are passed by calling
80 self.handle_entityref() or self.handle_charref() with the string
81 containing respectively the named or numeric reference as the
82 argument.
Fred Drake1d4601d2001-08-03 19:50:59 +000083 """
Guido van Rossum8846d712001-05-18 14:50:52 +000084
85 CDATA_CONTENT_ELEMENTS = ("script", "style")
86
Ezio Melotti6fc16d82014-08-02 18:36:12 +030087 def __init__(self, *, convert_charrefs=True):
R. David Murrayb579dba2010-12-03 04:06:39 +000088 """Initialize and reset this instance.
Guido van Rossum8846d712001-05-18 14:50:52 +000089
Ezio Melotti6fc16d82014-08-02 18:36:12 +030090 If convert_charrefs is True (the default), all character references
Ezio Melotti95401c52013-11-23 19:52:05 +020091 are automatically converted to the corresponding Unicode characters.
R. David Murrayb579dba2010-12-03 04:06:39 +000092 """
Ezio Melotti95401c52013-11-23 19:52:05 +020093 self.convert_charrefs = convert_charrefs
Guido van Rossum8846d712001-05-18 14:50:52 +000094 self.reset()
95
Guido van Rossum8846d712001-05-18 14:50:52 +000096 def reset(self):
Fred Drake1d4601d2001-08-03 19:50:59 +000097 """Reset this instance. Loses all unprocessed data."""
Guido van Rossum8846d712001-05-18 14:50:52 +000098 self.rawdata = ''
Guido van Rossum8846d712001-05-18 14:50:52 +000099 self.lasttag = '???'
Guido van Rossum8846d712001-05-18 14:50:52 +0000100 self.interesting = interesting_normal
Ezio Melotti7de56f62011-11-01 14:12:22 +0200101 self.cdata_elem = None
Fred Drakecb5c80f2007-12-07 11:10:11 +0000102 _markupbase.ParserBase.reset(self)
Guido van Rossum8846d712001-05-18 14:50:52 +0000103
Guido van Rossum8846d712001-05-18 14:50:52 +0000104 def feed(self, data):
Éric Araujo39f180b2011-05-04 15:55:47 +0200105 r"""Feed data to the parser.
Fred Drake1d4601d2001-08-03 19:50:59 +0000106
107 Call this as often as you want, with as little or as much text
108 as you want (may include '\n').
109 """
Guido van Rossum8846d712001-05-18 14:50:52 +0000110 self.rawdata = self.rawdata + data
111 self.goahead(0)
112
Guido van Rossum8846d712001-05-18 14:50:52 +0000113 def close(self):
Fred Drake1d4601d2001-08-03 19:50:59 +0000114 """Handle any buffered data."""
Guido van Rossum8846d712001-05-18 14:50:52 +0000115 self.goahead(1)
116
Guido van Rossum8846d712001-05-18 14:50:52 +0000117 __starttag_text = None
118
Guido van Rossum8846d712001-05-18 14:50:52 +0000119 def get_starttag_text(self):
Fred Drake1d4601d2001-08-03 19:50:59 +0000120 """Return full source of start tag: '<...>'."""
Guido van Rossum8846d712001-05-18 14:50:52 +0000121 return self.__starttag_text
122
Ezio Melotti7de56f62011-11-01 14:12:22 +0200123 def set_cdata_mode(self, elem):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200124 self.cdata_elem = elem.lower()
Ezio Melotti15cb4892011-11-18 18:01:49 +0200125 self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
Guido van Rossum8846d712001-05-18 14:50:52 +0000126
127 def clear_cdata_mode(self):
128 self.interesting = interesting_normal
Ezio Melotti7de56f62011-11-01 14:12:22 +0200129 self.cdata_elem = None
Guido van Rossum8846d712001-05-18 14:50:52 +0000130
131 # Internal -- handle data as far as reasonable. May leave state
132 # and data to be processed by a subsequent call. If 'end' is
133 # true, force handling all data as if followed by EOF marker.
134 def goahead(self, end):
135 rawdata = self.rawdata
136 i = 0
137 n = len(rawdata)
138 while i < n:
Ezio Melotti95401c52013-11-23 19:52:05 +0200139 if self.convert_charrefs and not self.cdata_elem:
140 j = rawdata.find('<', i)
141 if j < 0:
Ezio Melotti6f2bb982015-09-06 21:38:06 +0300142 # if we can't find the next <, either we are at the end
143 # or there's more text incoming. If the latter is True,
144 # we can't pass the text to handle_data in case we have
145 # a charref cut in half at end. Try to determine if
146 # this is the case before proceding by looking for an
147 # & near the end and see if it's followed by a space or ;.
148 amppos = rawdata.rfind('&', max(i, n-34))
149 if (amppos >= 0 and
150 not re.compile(r'[\s;]').search(rawdata, amppos)):
Ezio Melotti95401c52013-11-23 19:52:05 +0200151 break # wait till we get all the text
152 j = n
Guido van Rossum8846d712001-05-18 14:50:52 +0000153 else:
Ezio Melotti95401c52013-11-23 19:52:05 +0200154 match = self.interesting.search(rawdata, i) # < or &
155 if match:
156 j = match.start()
157 else:
158 if self.cdata_elem:
159 break
160 j = n
161 if i < j:
162 if self.convert_charrefs and not self.cdata_elem:
163 self.handle_data(unescape(rawdata[i:j]))
164 else:
165 self.handle_data(rawdata[i:j])
Guido van Rossum8846d712001-05-18 14:50:52 +0000166 i = self.updatepos(i, j)
167 if i == n: break
Fred Drake248b0432001-12-03 17:09:50 +0000168 startswith = rawdata.startswith
169 if startswith('<', i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000170 if starttagopen.match(rawdata, i): # < + letter
171 k = self.parse_starttag(i)
Fred Drake248b0432001-12-03 17:09:50 +0000172 elif startswith("</", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000173 k = self.parse_endtag(i)
Fred Drake248b0432001-12-03 17:09:50 +0000174 elif startswith("<!--", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000175 k = self.parse_comment(i)
Fred Drake248b0432001-12-03 17:09:50 +0000176 elif startswith("<?", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000177 k = self.parse_pi(i)
Fred Drake248b0432001-12-03 17:09:50 +0000178 elif startswith("<!", i):
Ezio Melotti73a43592014-08-02 14:10:30 +0300179 k = self.parse_html_declaration(i)
Fred Drake68eac2b2001-09-04 15:10:16 +0000180 elif (i + 1) < n:
Fred Drake029acfb2001-08-20 21:24:19 +0000181 self.handle_data("<")
182 k = i + 1
Fred Drake68eac2b2001-09-04 15:10:16 +0000183 else:
184 break
Guido van Rossum8846d712001-05-18 14:50:52 +0000185 if k < 0:
R. David Murrayb579dba2010-12-03 04:06:39 +0000186 if not end:
187 break
R. David Murrayb579dba2010-12-03 04:06:39 +0000188 k = rawdata.find('>', i + 1)
189 if k < 0:
190 k = rawdata.find('<', i + 1)
191 if k < 0:
192 k = i + 1
193 else:
194 k += 1
Ezio Melotti95401c52013-11-23 19:52:05 +0200195 if self.convert_charrefs and not self.cdata_elem:
196 self.handle_data(unescape(rawdata[i:k]))
197 else:
198 self.handle_data(rawdata[i:k])
Guido van Rossum8846d712001-05-18 14:50:52 +0000199 i = self.updatepos(i, k)
Fred Drake248b0432001-12-03 17:09:50 +0000200 elif startswith("&#", i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000201 match = charref.match(rawdata, i)
202 if match:
Fred Drake1d4601d2001-08-03 19:50:59 +0000203 name = match.group()[2:-1]
Guido van Rossum8846d712001-05-18 14:50:52 +0000204 self.handle_charref(name)
205 k = match.end()
Fred Drake248b0432001-12-03 17:09:50 +0000206 if not startswith(';', k-1):
Fred Drake029acfb2001-08-20 21:24:19 +0000207 k = k - 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000208 i = self.updatepos(i, k)
209 continue
Fred Drake68eac2b2001-09-04 15:10:16 +0000210 else:
Ezio Melottif27b9a72014-02-01 21:21:01 +0200211 if ";" in rawdata[i:]: # bail by consuming &#
212 self.handle_data(rawdata[i:i+2])
213 i = self.updatepos(i, i+2)
Fred Drake68eac2b2001-09-04 15:10:16 +0000214 break
Fred Drake248b0432001-12-03 17:09:50 +0000215 elif startswith('&', i):
Guido van Rossum8846d712001-05-18 14:50:52 +0000216 match = entityref.match(rawdata, i)
217 if match:
218 name = match.group(1)
219 self.handle_entityref(name)
220 k = match.end()
Fred Drake248b0432001-12-03 17:09:50 +0000221 if not startswith(';', k-1):
Fred Drake029acfb2001-08-20 21:24:19 +0000222 k = k - 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000223 i = self.updatepos(i, k)
224 continue
Fred Drake029acfb2001-08-20 21:24:19 +0000225 match = incomplete.match(rawdata, i)
226 if match:
Fred Drake68eac2b2001-09-04 15:10:16 +0000227 # match.group() will contain at least 2 chars
Fred Drake248b0432001-12-03 17:09:50 +0000228 if end and match.group() == rawdata[i:]:
Ezio Melotti73a43592014-08-02 14:10:30 +0300229 k = match.end()
230 if k <= i:
231 k = n
232 i = self.updatepos(i, i + 1)
Fred Drake68eac2b2001-09-04 15:10:16 +0000233 # incomplete
234 break
235 elif (i + 1) < n:
236 # not the end of the buffer, and can't be confused
237 # with some other construct
238 self.handle_data("&")
239 i = self.updatepos(i, i + 1)
240 else:
241 break
Guido van Rossum8846d712001-05-18 14:50:52 +0000242 else:
243 assert 0, "interesting.search() lied"
244 # end while
Ezio Melotti15cb4892011-11-18 18:01:49 +0200245 if end and i < n and not self.cdata_elem:
Ezio Melotti95401c52013-11-23 19:52:05 +0200246 if self.convert_charrefs and not self.cdata_elem:
247 self.handle_data(unescape(rawdata[i:n]))
248 else:
249 self.handle_data(rawdata[i:n])
Guido van Rossum8846d712001-05-18 14:50:52 +0000250 i = self.updatepos(i, n)
251 self.rawdata = rawdata[i:]
252
Ezio Melottif4ab4912012-02-13 15:50:37 +0200253 # Internal -- parse html declarations, return length or -1 if not terminated
254 # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
255 # See also parse_declaration in _markupbase
256 def parse_html_declaration(self, i):
257 rawdata = self.rawdata
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200258 assert rawdata[i:i+2] == '<!', ('unexpected call to '
259 'parse_html_declaration()')
Ezio Melottif4ab4912012-02-13 15:50:37 +0200260 if rawdata[i:i+4] == '<!--':
Ezio Melottie31dded2012-02-13 20:20:00 +0200261 # this case is actually already handled in goahead()
Ezio Melottif4ab4912012-02-13 15:50:37 +0200262 return self.parse_comment(i)
263 elif rawdata[i:i+3] == '<![':
264 return self.parse_marked_section(i)
265 elif rawdata[i:i+9].lower() == '<!doctype':
266 # find the closing >
Ezio Melottie31dded2012-02-13 20:20:00 +0200267 gtpos = rawdata.find('>', i+9)
Ezio Melottif4ab4912012-02-13 15:50:37 +0200268 if gtpos == -1:
269 return -1
270 self.handle_decl(rawdata[i+2:gtpos])
271 return gtpos+1
272 else:
273 return self.parse_bogus_comment(i)
274
Ezio Melottifa3702d2012-02-10 10:45:44 +0200275 # Internal -- parse bogus comment, return length or -1 if not terminated
276 # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
277 def parse_bogus_comment(self, i, report=1):
278 rawdata = self.rawdata
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200279 assert rawdata[i:i+2] in ('<!', '</'), ('unexpected call to '
280 'parse_comment()')
Ezio Melottifa3702d2012-02-10 10:45:44 +0200281 pos = rawdata.find('>', i+2)
282 if pos == -1:
283 return -1
284 if report:
285 self.handle_comment(rawdata[i+2:pos])
286 return pos + 1
287
Guido van Rossum8846d712001-05-18 14:50:52 +0000288 # Internal -- parse processing instr, return end or -1 if not terminated
289 def parse_pi(self, i):
290 rawdata = self.rawdata
291 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
292 match = piclose.search(rawdata, i+2) # >
293 if not match:
294 return -1
295 j = match.start()
296 self.handle_pi(rawdata[i+2: j])
297 j = match.end()
298 return j
299
300 # Internal -- handle starttag, return end or -1 if not terminated
301 def parse_starttag(self, i):
302 self.__starttag_text = None
303 endpos = self.check_for_whole_start_tag(i)
304 if endpos < 0:
305 return endpos
306 rawdata = self.rawdata
307 self.__starttag_text = rawdata[i:endpos]
308
309 # Now parse the data between i+1 and j into a tag and attrs
310 attrs = []
Ezio Melotti73a43592014-08-02 14:10:30 +0300311 match = tagfind_tolerant.match(rawdata, i+1)
Guido van Rossum8846d712001-05-18 14:50:52 +0000312 assert match, 'unexpected call to parse_starttag()'
313 k = match.end()
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600314 self.lasttag = tag = match.group(1).lower()
Guido van Rossum8846d712001-05-18 14:50:52 +0000315 while k < endpos:
Ezio Melotti73a43592014-08-02 14:10:30 +0300316 m = attrfind_tolerant.match(rawdata, k)
Guido van Rossum8846d712001-05-18 14:50:52 +0000317 if not m:
318 break
319 attrname, rest, attrvalue = m.group(1, 2, 3)
320 if not rest:
321 attrvalue = None
322 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
323 attrvalue[:1] == '"' == attrvalue[-1:]:
324 attrvalue = attrvalue[1:-1]
Ezio Melottic2fe5772011-11-14 18:53:33 +0200325 if attrvalue:
Ezio Melotti4a9ee262013-11-19 20:28:45 +0200326 attrvalue = unescape(attrvalue)
Fred Drake248b0432001-12-03 17:09:50 +0000327 attrs.append((attrname.lower(), attrvalue))
Guido van Rossum8846d712001-05-18 14:50:52 +0000328 k = m.end()
329
Fred Drake248b0432001-12-03 17:09:50 +0000330 end = rawdata[k:endpos].strip()
Guido van Rossum8846d712001-05-18 14:50:52 +0000331 if end not in (">", "/>"):
332 lineno, offset = self.getpos()
333 if "\n" in self.__starttag_text:
Fred Drake248b0432001-12-03 17:09:50 +0000334 lineno = lineno + self.__starttag_text.count("\n")
Guido van Rossum8846d712001-05-18 14:50:52 +0000335 offset = len(self.__starttag_text) \
Fred Drake248b0432001-12-03 17:09:50 +0000336 - self.__starttag_text.rfind("\n")
Guido van Rossum8846d712001-05-18 14:50:52 +0000337 else:
338 offset = offset + len(self.__starttag_text)
R. David Murrayb579dba2010-12-03 04:06:39 +0000339 self.handle_data(rawdata[i:endpos])
340 return endpos
Fred Drake248b0432001-12-03 17:09:50 +0000341 if end.endswith('/>'):
Guido van Rossum8846d712001-05-18 14:50:52 +0000342 # XHTML-style empty tag: <span attr="value" />
343 self.handle_startendtag(tag, attrs)
344 else:
345 self.handle_starttag(tag, attrs)
346 if tag in self.CDATA_CONTENT_ELEMENTS:
Ezio Melotti7de56f62011-11-01 14:12:22 +0200347 self.set_cdata_mode(tag)
Guido van Rossum8846d712001-05-18 14:50:52 +0000348 return endpos
349
350 # Internal -- check to see if we have a complete starttag; return end
351 # or -1 if incomplete.
352 def check_for_whole_start_tag(self, i):
353 rawdata = self.rawdata
Ezio Melotti73a43592014-08-02 14:10:30 +0300354 m = locatestarttagend_tolerant.match(rawdata, i)
Guido van Rossum8846d712001-05-18 14:50:52 +0000355 if m:
356 j = m.end()
357 next = rawdata[j:j+1]
358 if next == ">":
359 return j + 1
360 if next == "/":
Fred Drake248b0432001-12-03 17:09:50 +0000361 if rawdata.startswith("/>", j):
Guido van Rossum8846d712001-05-18 14:50:52 +0000362 return j + 2
Fred Drake248b0432001-12-03 17:09:50 +0000363 if rawdata.startswith("/", j):
Guido van Rossum8846d712001-05-18 14:50:52 +0000364 # buffer boundary
365 return -1
366 # else bogus input
R. David Murrayb579dba2010-12-03 04:06:39 +0000367 if j > i:
368 return j
369 else:
370 return i + 1
Guido van Rossum8846d712001-05-18 14:50:52 +0000371 if next == "":
372 # end of input
373 return -1
374 if next in ("abcdefghijklmnopqrstuvwxyz=/"
375 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
376 # end of input in or before attribute value, or we have the
377 # '/' from a '/>' ending
378 return -1
R. David Murrayb579dba2010-12-03 04:06:39 +0000379 if j > i:
380 return j
381 else:
382 return i + 1
Fred Drakebfc8fea2001-09-24 20:10:28 +0000383 raise AssertionError("we should not get here!")
Guido van Rossum8846d712001-05-18 14:50:52 +0000384
385 # Internal -- parse endtag, return end or -1 if incomplete
386 def parse_endtag(self, i):
387 rawdata = self.rawdata
388 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
389 match = endendtag.search(rawdata, i+1) # >
390 if not match:
391 return -1
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200392 gtpos = match.end()
Guido van Rossum8846d712001-05-18 14:50:52 +0000393 match = endtagfind.match(rawdata, i) # </ + tag + >
394 if not match:
Ezio Melotti7de56f62011-11-01 14:12:22 +0200395 if self.cdata_elem is not None:
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200396 self.handle_data(rawdata[i:gtpos])
397 return gtpos
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200398 # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
399 namematch = tagfind_tolerant.match(rawdata, i+2)
400 if not namematch:
401 # w3.org/TR/html5/tokenization.html#end-tag-open-state
402 if rawdata[i:i+3] == '</>':
403 return i+3
404 else:
405 return self.parse_bogus_comment(i)
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200406 tagname = namematch.group(1).lower()
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200407 # consume and ignore other stuff between the name and the >
408 # Note: this is not 100% correct, since we might have things like
409 # </tag attr=">">, but looking for > after tha name should cover
410 # most of the cases and is much simpler
411 gtpos = rawdata.find('>', namematch.end())
412 self.handle_endtag(tagname)
413 return gtpos+1
Ezio Melotti7de56f62011-11-01 14:12:22 +0200414
415 elem = match.group(1).lower() # script or style
416 if self.cdata_elem is not None:
417 if elem != self.cdata_elem:
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200418 self.handle_data(rawdata[i:gtpos])
419 return gtpos
Ezio Melotti7de56f62011-11-01 14:12:22 +0200420
421 self.handle_endtag(elem.lower())
Fred Drake30d59ba2002-05-14 15:50:11 +0000422 self.clear_cdata_mode()
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200423 return gtpos
Guido van Rossum8846d712001-05-18 14:50:52 +0000424
425 # Overridable -- finish processing of start+end tag: <tag.../>
426 def handle_startendtag(self, tag, attrs):
427 self.handle_starttag(tag, attrs)
428 self.handle_endtag(tag)
429
430 # Overridable -- handle start tag
431 def handle_starttag(self, tag, attrs):
432 pass
433
434 # Overridable -- handle end tag
435 def handle_endtag(self, tag):
436 pass
437
438 # Overridable -- handle character reference
439 def handle_charref(self, name):
440 pass
441
442 # Overridable -- handle entity reference
443 def handle_entityref(self, name):
444 pass
445
446 # Overridable -- handle data
447 def handle_data(self, data):
448 pass
449
450 # Overridable -- handle comment
451 def handle_comment(self, data):
452 pass
453
454 # Overridable -- handle declaration
455 def handle_decl(self, decl):
456 pass
457
458 # Overridable -- handle processing instruction
459 def handle_pi(self, data):
460 pass
461
Fred Drakebfc8fea2001-09-24 20:10:28 +0000462 def unknown_decl(self, data):
Ezio Melotti73a43592014-08-02 14:10:30 +0300463 pass
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200464
465 # Internal -- helper to remove special character quoting
466 def unescape(self, s):
467 warnings.warn('The unescape method is deprecated and will be removed '
468 'in 3.5, use html.unescape() instead.',
469 DeprecationWarning, stacklevel=2)
470 return unescape(s)