Debian Codegraph @

lib-python/3/html/parser.py

raw symbols SCIP
1 """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
11 import re
12 import _markupbase
13
14 from html import unescape
15
16
17 __all__ = ['HTMLParser']
18
19 # Regular expressions used for parsing
20
21 interesting_normal = re.compile('[&<]')
22 incomplete = re.compile('&[a-zA-Z#]')
23
24 entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
25 charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
26
27 starttagopen = re.compile('<[a-zA-Z]')
28 endtagopen = re.compile('</[a-zA-Z]')
29 piclose = re.compile('>')
30 commentclose = re.compile(r'--!?>')
31 commentabruptclose = re.compile(r'-?>')
32 # Note:
33 # 1) if you change tagfind/attrfind remember to update locatetagend too;
34 # 2) if you change tagfind/attrfind and/or locatetagend the parser will
35 # explode, so don't do it.
36 # see the HTML5 specs section "13.2.5.6 Tag open state",
37 # "13.2.5.8 Tag name state" and "13.2.5.33 Attribute name state".
38 # https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
39 # https://html.spec.whatwg.org/multipage/parsing.html#tag-name-state
40 # https://html.spec.whatwg.org/multipage/parsing.html#attribute-name-state
41 tagfind_tolerant = re.compile(r'([a-zA-Z][^\t\n\r\f />]*)(?:[\t\n\r\f ]|/(?!>))*')
42 attrfind_tolerant = re.compile(r"""
43 (
44 (?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name
45 )
46 ([\t\n\r\f ]*=[\t\n\r\f ]* # value indicator
47 ('[^']*' # LITA-enclosed value
48 |"[^"]*" # LIT-enclosed value
49 |(?!['"])[^>\t\n\r\f ]* # bare value
50 )
51 )?
52 (?:[\t\n\r\f ]|/(?!>))* # possibly followed by a space
53 """, re.VERBOSE)
54 locatetagend = re.compile(r"""
55 [a-zA-Z][^\t\n\r\f />]* # tag name
56 [\t\n\r\f /]* # optional whitespace before attribute name
57 (?:(?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name
58 (?:[\t\n\r\f ]*=[\t\n\r\f ]* # value indicator
59 (?:'[^']*' # LITA-enclosed value
60 |"[^"]*" # LIT-enclosed value
61 |(?!['"])[^>\t\n\r\f ]* # bare value
62 )
63 )?
64 [\t\n\r\f /]* # possibly followed by a space
65 )*
66 >?
67 """, re.VERBOSE)
68 # The following variables are not used, but are temporarily left for
69 # backward compatibility.
70 locatestarttagend_tolerant = re.compile(r"""
71 <[a-zA-Z][^\t\n\r\f />\x00]* # tag name
72 (?:[\s/]* # optional whitespace before attribute name
73 (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name
74 (?:\s*=+\s* # value indicator
75 (?:'[^']*' # LITA-enclosed value
76 |"[^"]*" # LIT-enclosed value
77 |(?!['"])[^>\s]* # bare value
78 )
79 \s* # possibly followed by a space
80 )?(?:\s|/(?!>))*
81 )*
82 )?
83 \s* # trailing whitespace
84 """, re.VERBOSE)
85 endendtag = re.compile('>')
86 endtagfind = re.compile(r'</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
87
88
89
90 class HTMLParser(_markupbase.ParserBase):
91 """Find tags and other markup and call handler functions.
92
93 Usage:
94 p = HTMLParser()
95 p.feed(data)
96 ...
97 p.close()
98
99 Start tags are handled by calling self.handle_starttag() or
100 self.handle_startendtag(); end tags by self.handle_endtag(). The
101 data between tags is passed from the parser to the derived class
102 by calling self.handle_data() with the data as argument (the data
103 may be split up in arbitrary chunks). If convert_charrefs is
104 True the character references are converted automatically to the
105 corresponding Unicode character (and self.handle_data() is no
106 longer split in chunks), otherwise they are passed by calling
107 self.handle_entityref() or self.handle_charref() with the string
108 containing respectively the named or numeric reference as the
109 argument.
110 """
111
112 # See the HTML5 specs section "13.4 Parsing HTML fragments".
113 # https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
114 # CDATA_CONTENT_ELEMENTS are parsed in RAWTEXT mode
115 CDATA_CONTENT_ELEMENTS = ("script", "style", "xmp", "iframe", "noembed", "noframes")
116 RCDATA_CONTENT_ELEMENTS = ("textarea", "title")
117
118 def __init__(self, *, convert_charrefs=True, scripting=False):
119 """Initialize and reset this instance.
120
121 If convert_charrefs is true (the default), all character references
122 are automatically converted to the corresponding Unicode characters.
123
124 If *scripting* is false (the default), the content of the
125 ``noscript`` element is parsed normally; if it's true,
126 it's returned as is without being parsed.
127 """
128 self.convert_charrefs = convert_charrefs
129 self.scripting = scripting
130 self.reset()
131
132 def reset(self):
133 """Reset this instance. Loses all unprocessed data."""
134 self.rawdata = ''
135 self.lasttag = '???'
136 self.interesting = interesting_normal
137 self.cdata_elem = None
138 self._support_cdata = True
139 self._escapable = True
140 _markupbase.ParserBase.reset(self)
141
142 def feed(self, data):
143 r"""Feed data to the parser.
144
145 Call this as often as you want, with as little or as much text
146 as you want (may include '\n').
147 """
148 self.rawdata = self.rawdata + data
149 self.goahead(0)
150
151 def close(self):
152 """Handle any buffered data."""
153 self.goahead(1)
154
155 __starttag_text = None
156
157 def get_starttag_text(self):
158 """Return full source of start tag: '<...>'."""
159 return self.__starttag_text
160
161 def set_cdata_mode(self, elem, *, escapable=False):
162 self.cdata_elem = elem.lower()
163 self._escapable = escapable
164 if self.cdata_elem == 'plaintext':
165 self.interesting = re.compile(r'\Z')
166 elif escapable and not self.convert_charrefs:
167 self.interesting = re.compile(r'&|</%s(?=[\t\n\r\f />])' % self.cdata_elem,
168 re.IGNORECASE|re.ASCII)
169 else:
170 self.interesting = re.compile(r'</%s(?=[\t\n\r\f />])' % self.cdata_elem,
171 re.IGNORECASE|re.ASCII)
172
173 def clear_cdata_mode(self):
174 self.interesting = interesting_normal
175 self.cdata_elem = None
176 self._escapable = True
177
178 def _set_support_cdata(self, flag=True):
179 """Enable or disable support of the CDATA sections.
180 If enabled, "<[CDATA[" starts a CDATA section which ends with "]]>".
181 If disabled, "<[CDATA[" starts a bogus comments which ends with ">".
182
183 This method is not called by default. Its purpose is to be called
184 in custom handle_starttag() and handle_endtag() methods, with
185 value that depends on the adjusted current node.
186 See https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
187 for details.
188 """
189 self._support_cdata = flag
190
191 # Internal -- handle data as far as reasonable. May leave state
192 # and data to be processed by a subsequent call. If 'end' is
193 # true, force handling all data as if followed by EOF marker.
194 def goahead(self, end):
195 rawdata = self.rawdata
196 i = 0
197 n = len(rawdata)
198 while i < n:
199 if self.convert_charrefs and not self.cdata_elem:
200 j = rawdata.find('<', i)
201 if j < 0:
202 # if we can't find the next <, either we are at the end
203 # or there's more text incoming. If the latter is True,
204 # we can't pass the text to handle_data in case we have
205 # a charref cut in half at end. Try to determine if
206 # this is the case before proceeding by looking for an
207 # & near the end and see if it's followed by a space or ;.
208 amppos = rawdata.rfind('&', max(i, n-34))
209 if (amppos >= 0 and
210 not re.compile(r'[\t\n\r\f ;]').search(rawdata, amppos)):
211 break # wait till we get all the text
212 j = n
213 else:
214 match = self.interesting.search(rawdata, i) # < or &
215 if match:
216 j = match.start()
217 else:
218 if self.cdata_elem:
219 break
220 j = n
221 if i < j:
222 if self.convert_charrefs and self._escapable:
223 self.handle_data(unescape(rawdata[i:j]))
224 else:
225 self.handle_data(rawdata[i:j])
226 i = self.updatepos(i, j)
227 if i == n: break
228 startswith = rawdata.startswith
229 if startswith('<', i):
230 if starttagopen.match(rawdata, i): # < + letter
231 k = self.parse_starttag(i)
232 elif startswith("</", i):
233 k = self.parse_endtag(i)
234 elif startswith("<!--", i):
235 k = self.parse_comment(i)
236 elif startswith("<?", i):
237 k = self.parse_pi(i)
238 elif startswith("<!", i):
239 k = self.parse_html_declaration(i)
240 elif (i + 1) < n or end:
241 self.handle_data("<")
242 k = i + 1
243 else:
244 break
245 if k < 0:
246 if not end:
247 break
248 if starttagopen.match(rawdata, i): # < + letter
249 pass
250 elif startswith("</", i):
251 if i + 2 == n:
252 self.handle_data("</")
253 elif endtagopen.match(rawdata, i): # </ + letter
254 pass
255 else:
256 # bogus comment
257 self.handle_comment(rawdata[i+2:])
258 elif startswith("<!--", i):
259 j = n
260 for suffix in ("--!", "--", "-"):
261 if rawdata.endswith(suffix, i+4):
262 j -= len(suffix)
263 break
264 self.handle_comment(rawdata[i+4:j])
265 elif startswith("<![CDATA[", i) and self._support_cdata:
266 self.unknown_decl(rawdata[i+3:])
267 elif rawdata[i:i+9].lower() == '<!doctype':
268 self.handle_decl(rawdata[i+2:])
269 elif startswith("<!", i):
270 # bogus comment
271 self.handle_comment(rawdata[i+2:])
272 elif startswith("<?", i):
273 self.handle_pi(rawdata[i+2:])
274 else:
275 raise AssertionError("we should not get here!")
276 k = n
277 i = self.updatepos(i, k)
278 elif startswith("&#", i):
279 match = charref.match(rawdata, i)
280 if match:
281 name = match.group()[2:-1]
282 self.handle_charref(name)
283 k = match.end()
284 if not startswith(';', k-1):
285 k = k - 1
286 i = self.updatepos(i, k)
287 continue
288 else:
289 if ";" in rawdata[i:]: # bail by consuming &#
290 self.handle_data(rawdata[i:i+2])
291 i = self.updatepos(i, i+2)
292 break
293 elif startswith('&', i):
294 match = entityref.match(rawdata, i)
295 if match:
296 name = match.group(1)
297 self.handle_entityref(name)
298 k = match.end()
299 if not startswith(';', k-1):
300 k = k - 1
301 i = self.updatepos(i, k)
302 continue
303 match = incomplete.match(rawdata, i)
304 if match:
305 # match.group() will contain at least 2 chars
306 if end and match.group() == rawdata[i:]:
307 k = match.end()
308 if k <= i:
309 k = n
310 i = self.updatepos(i, i + 1)
311 # incomplete
312 break
313 elif (i + 1) < n:
314 # not the end of the buffer, and can't be confused
315 # with some other construct
316 self.handle_data("&")
317 i = self.updatepos(i, i + 1)
318 else:
319 break
320 else:
321 assert 0, "interesting.search() lied"
322 # end while
323 if end and i < n:
324 if self.convert_charrefs and self._escapable:
325 self.handle_data(unescape(rawdata[i:n]))
326 else:
327 self.handle_data(rawdata[i:n])
328 i = self.updatepos(i, n)
329 self.rawdata = rawdata[i:]
330
331 # Internal -- parse html declarations, return length or -1 if not terminated
332 # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
333 # See also parse_declaration in _markupbase
334 def parse_html_declaration(self, i):
335 rawdata = self.rawdata
336 assert rawdata[i:i+2] == '<!', ('unexpected call to '
337 'parse_html_declaration()')
338 if rawdata[i:i+4] == '<!--':
339 # this case is actually already handled in goahead()
340 return self.parse_comment(i)
341 elif rawdata[i:i+9] == '<![CDATA[' and self._support_cdata:
342 j = rawdata.find(']]>', i+9)
343 if j < 0:
344 return -1
345 self.unknown_decl(rawdata[i+3: j])
346 return j + 3
347 elif rawdata[i:i+9].lower() == '<!doctype':
348 # find the closing >
349 gtpos = rawdata.find('>', i+9)
350 if gtpos == -1:
351 return -1
352 self.handle_decl(rawdata[i+2:gtpos])
353 return gtpos+1
354 elif rawdata[i:i+3] == '<![':
355 j = rawdata.find('>', i+3)
356 if j < 0:
357 return -1
358 if rawdata[j-1] == ']':
359 self.unknown_decl(rawdata[i+3: j-1])
360 else:
361 self.handle_comment(rawdata[i+2: j])
362 return j + 1
363 else:
364 return self.parse_bogus_comment(i)
365
366 # Internal -- parse comment, return length or -1 if not terminated
367 # see https://html.spec.whatwg.org/multipage/parsing.html#comment-start-state
368 def parse_comment(self, i, report=True):
369 rawdata = self.rawdata
370 assert rawdata.startswith('<!--', i), 'unexpected call to parse_comment()'
371 match = commentclose.search(rawdata, i+4)
372 if not match:
373 match = commentabruptclose.match(rawdata, i+4)
374 if not match:
375 return -1
376 if report:
377 j = match.start()
378 self.handle_comment(rawdata[i+4: j])
379 return match.end()
380
381 # Internal -- parse bogus comment, return length or -1 if not terminated
382 # see https://html.spec.whatwg.org/multipage/parsing.html#bogus-comment-state
383 def parse_bogus_comment(self, i, report=1):
384 rawdata = self.rawdata
385 assert rawdata[i:i+2] in ('<!', '</'), ('unexpected call to '
386 'parse_comment()')
387 pos = rawdata.find('>', i+2)
388 if pos == -1:
389 return -1
390 if report:
391 self.handle_comment(rawdata[i+2:pos])
392 return pos + 1
393
394 # Internal -- parse processing instr, return end or -1 if not terminated
395 def parse_pi(self, i):
396 rawdata = self.rawdata
397 assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
398 match = piclose.search(rawdata, i+2) # >
399 if not match:
400 return -1
401 j = match.start()
402 self.handle_pi(rawdata[i+2: j])
403 j = match.end()
404 return j
405
406 # Internal -- handle starttag, return end or -1 if not terminated
407 def parse_starttag(self, i):
408 # See the HTML5 specs section "13.2.5.8 Tag name state"
409 # https://html.spec.whatwg.org/multipage/parsing.html#tag-name-state
410 self.__starttag_text = None
411 endpos = self.check_for_whole_start_tag(i)
412 if endpos < 0:
413 return endpos
414 rawdata = self.rawdata
415 self.__starttag_text = rawdata[i:endpos]
416
417 # Now parse the data between i+1 and j into a tag and attrs
418 attrs = []
419 match = tagfind_tolerant.match(rawdata, i+1)
420 assert match, 'unexpected call to parse_starttag()'
421 k = match.end()
422 self.lasttag = tag = match.group(1).lower()
423 while k < endpos:
424 m = attrfind_tolerant.match(rawdata, k)
425 if not m:
426 break
427 attrname, rest, attrvalue = m.group(1, 2, 3)
428 if not rest:
429 attrvalue = None
430 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
431 attrvalue[:1] == '"' == attrvalue[-1:]:
432 attrvalue = attrvalue[1:-1]
433 if attrvalue:
434 attrvalue = unescape(attrvalue)
435 attrs.append((attrname.lower(), attrvalue))
436 k = m.end()
437
438 end = rawdata[k:endpos].strip()
439 if end not in (">", "/>"):
440 self.handle_data(rawdata[i:endpos])
441 return endpos
442 if end.endswith('/>'):
443 # XHTML-style empty tag: <span attr="value" />
444 self.handle_startendtag(tag, attrs)
445 else:
446 self.handle_starttag(tag, attrs)
447 if (tag in self.CDATA_CONTENT_ELEMENTS or
448 (self.scripting and tag == "noscript") or
449 tag == "plaintext"):
450 self.set_cdata_mode(tag, escapable=False)
451 elif tag in self.RCDATA_CONTENT_ELEMENTS:
452 self.set_cdata_mode(tag, escapable=True)
453 return endpos
454
455 # Internal -- check to see if we have a complete starttag; return end
456 # or -1 if incomplete.
457 def check_for_whole_start_tag(self, i):
458 rawdata = self.rawdata
459 match = locatetagend.match(rawdata, i+1)
460 assert match
461 j = match.end()
462 if rawdata[j-1] != ">":
463 return -1
464 return j
465
466 # Internal -- parse endtag, return end or -1 if incomplete
467 def parse_endtag(self, i):
468 # See the HTML5 specs section "13.2.5.7 End tag open state"
469 # https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
470 rawdata = self.rawdata
471 assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
472 if rawdata.find('>', i+2) < 0: # fast check
473 return -1
474 if not endtagopen.match(rawdata, i): # </ + letter
475 if rawdata[i+2:i+3] == '>': # </> is ignored
476 # "missing-end-tag-name" parser error
477 return i+3
478 else:
479 return self.parse_bogus_comment(i)
480
481 match = locatetagend.match(rawdata, i+2)
482 assert match
483 j = match.end()
484 if rawdata[j-1] != ">":
485 return -1
486
487 # find the name: "13.2.5.8 Tag name state"
488 # https://html.spec.whatwg.org/multipage/parsing.html#tag-name-state
489 match = tagfind_tolerant.match(rawdata, i+2)
490 assert match
491 tag = match.group(1).lower()
492 self.handle_endtag(tag)
493 self.clear_cdata_mode()
494 return j
495
496 # Overridable -- finish processing of start+end tag: <tag.../>
497 def handle_startendtag(self, tag, attrs):
498 self.handle_starttag(tag, attrs)
499 self.handle_endtag(tag)
500
501 # Overridable -- handle start tag
502 def handle_starttag(self, tag, attrs):
503 pass
504
505 # Overridable -- handle end tag
506 def handle_endtag(self, tag):
507 pass
508
509 # Overridable -- handle character reference
510 def handle_charref(self, name):
511 pass
512
513 # Overridable -- handle entity reference
514 def handle_entityref(self, name):
515 pass
516
517 # Overridable -- handle data
518 def handle_data(self, data):
519 pass
520
521 # Overridable -- handle comment
522 def handle_comment(self, data):
523 pass
524
525 # Overridable -- handle declaration
526 def handle_decl(self, decl):
527 pass
528
529 # Overridable -- handle processing instruction
530 def handle_pi(self, data):
531 pass
532
533 def unknown_decl(self, data):
534 pass