1# encoding: utf-8
2"""Use the HTMLParser library to parse HTML files that aren't too bad."""
3from __future__ import annotations
4
5# Use of this source code is governed by the MIT license.
6__license__ = "MIT"
7
8__all__ = [
9 "HTMLParserTreeBuilder",
10]
11
12from html.parser import HTMLParser
13
14from typing import (
15 Any,
16 Callable,
17 cast,
18 Dict,
19 Iterable,
20 List,
21 Optional,
22 TYPE_CHECKING,
23 Tuple,
24 Type,
25 Union,
26)
27
28from bs4.element import (
29 AttributeDict,
30 CData,
31 Comment,
32 Declaration,
33 Doctype,
34 ProcessingInstruction,
35)
36from bs4.dammit import EntitySubstitution, UnicodeDammit
37
38from bs4.builder import (
39 DetectsXMLParsedAsHTML,
40 HTML,
41 HTMLTreeBuilder,
42 STRICT,
43)
44
45from bs4.exceptions import ParserRejectedMarkup
46
47if TYPE_CHECKING:
48 from bs4 import BeautifulSoup
49 from bs4.element import NavigableString
50 from bs4._typing import (
51 _Encoding,
52 _Encodings,
53 _RawMarkup,
54 )
55
56HTMLPARSER = "html.parser"
57
58_DuplicateAttributeHandler = Callable[[Dict[str, str], str, str], None]
59
60
61class BeautifulSoupHTMLParser(HTMLParser, DetectsXMLParsedAsHTML):
62 #: Constant to handle duplicate attributes by ignoring later values
63 #: and keeping the earlier ones.
64 REPLACE: str = "replace"
65
66 #: Constant to handle duplicate attributes by replacing earlier values
67 #: with later ones.
68 IGNORE: str = "ignore"
69
70 """A subclass of the Python standard library's HTMLParser class, which
71 listens for HTMLParser events and translates them into calls
72 to Beautiful Soup's tree construction API.
73
74 :param on_duplicate_attribute: A strategy for what to do if a
75 tag includes the same attribute more than once. Accepted
76 values are: REPLACE (replace earlier values with later
77 ones, the default), IGNORE (keep the earliest value
78 encountered), or a callable. A callable must take three
79 arguments: the dictionary of attributes already processed,
80 the name of the duplicate attribute, and the most recent value
81 encountered.
82 """
83
84 def __init__(
85 self,
86 soup: BeautifulSoup,
87 *args: Any,
88 on_duplicate_attribute: Union[str, _DuplicateAttributeHandler] = REPLACE,
89 **kwargs: Any,
90 ):
91 self.soup = soup
92 self.on_duplicate_attribute = on_duplicate_attribute
93 self.attribute_dict_class = soup.builder.attribute_dict_class
94 HTMLParser.__init__(self, *args, **kwargs)
95
96 # Keep a list of empty-element tags that were encountered
97 # without an explicit closing tag. If we encounter a closing tag
98 # of this type, we'll associate it with one of those entries.
99 #
100 # This isn't a stack because we don't care about the
101 # order. It's a list of closing tags we've already handled and
102 # will ignore, assuming they ever show up.
103 self.already_closed_empty_element = []
104
105 self._initialize_xml_detector()
106
107 on_duplicate_attribute: Union[str, _DuplicateAttributeHandler]
108 already_closed_empty_element: List[str]
109 soup: BeautifulSoup
110
111 def error(self, message: str) -> None:
112 # NOTE: This method is required so long as Python 3.9 is
113 # supported. The corresponding code is removed from HTMLParser
114 # in 3.5, but not removed from ParserBase until 3.10.
115 # https://github.com/python/cpython/issues/76025
116 #
117 # The original implementation turned the error into a warning,
118 # but in every case I discovered, this made HTMLParser
119 # immediately crash with an error message that was less
120 # helpful than the warning. The new implementation makes it
121 # more clear that html.parser just can't parse this
122 # markup. The 3.10 implementation does the same, though it
123 # raises AssertionError rather than calling a method. (We
124 # catch this error and wrap it in a ParserRejectedMarkup.)
125 raise ParserRejectedMarkup(message)
126
127 def handle_startendtag(
128 self, tag: str, attrs: List[Tuple[str, Optional[str]]]
129 ) -> None:
130 """Handle an incoming empty-element tag.
131
132 html.parser only calls this method when the markup looks like
133 <tag/>.
134 """
135 # `handle_empty_element` tells handle_starttag not to close the tag
136 # just because its name matches a known empty-element tag. We
137 # know that this is an empty-element tag, and we want to call
138 # handle_endtag ourselves.
139 self.handle_starttag(tag, attrs, handle_empty_element=False)
140 self.handle_endtag(tag)
141
142 def handle_starttag(
143 self,
144 tag: str,
145 attrs: List[Tuple[str, Optional[str]]],
146 handle_empty_element: bool = True,
147 ) -> None:
148 """Handle an opening tag, e.g. '<tag>'
149
150 :param handle_empty_element: True if this tag is known to be
151 an empty-element tag (i.e. there is not expected to be any
152 closing tag).
153 """
154 # TODO: handle namespaces here?
155 attr_dict: AttributeDict = self.attribute_dict_class()
156 for key, value in attrs:
157 # Change None attribute values to the empty string
158 # for consistency with the other tree builders.
159 if value is None:
160 value = ""
161 if key in attr_dict:
162 # A single attribute shows up multiple times in this
163 # tag. How to handle it depends on the
164 # on_duplicate_attribute setting.
165 on_dupe = self.on_duplicate_attribute
166 if on_dupe == self.IGNORE:
167 pass
168 elif on_dupe in (None, self.REPLACE):
169 attr_dict[key] = value
170 else:
171 on_dupe = cast(_DuplicateAttributeHandler, on_dupe)
172 on_dupe(attr_dict, key, value)
173 else:
174 attr_dict[key] = value
175 # print("START", tag)
176 sourceline: Optional[int]
177 sourcepos: Optional[int]
178 if self.soup.builder.store_line_numbers:
179 sourceline, sourcepos = self.getpos()
180 else:
181 sourceline = sourcepos = None
182 tagObj = self.soup.handle_starttag(
183 tag, None, None, attr_dict, sourceline=sourceline, sourcepos=sourcepos
184 )
185 if tagObj is not None and tagObj.is_empty_element and handle_empty_element:
186 # Unlike other parsers, html.parser doesn't send separate end tag
187 # events for empty-element tags. (It's handled in
188 # handle_startendtag, but only if the original markup looked like
189 # <tag/>.)
190 #
191 # So we need to call handle_endtag() ourselves. Since we
192 # know the start event is identical to the end event, we
193 # don't want handle_endtag() to cross off any previous end
194 # events for tags of this name.
195 self.handle_endtag(tag, check_already_closed=False)
196
197 # But we might encounter an explicit closing tag for this tag
198 # later on. If so, we want to ignore it.
199 self.already_closed_empty_element.append(tag)
200
201 if self._root_tag_name is None:
202 self._root_tag_encountered(tag)
203
204 def handle_endtag(self, tag: str, check_already_closed: bool = True) -> None:
205 """Handle a closing tag, e.g. '</tag>'
206
207 :param tag: A tag name.
208 :param check_already_closed: True if this tag is expected to
209 be the closing portion of an empty-element tag,
210 e.g. '<tag></tag>'.
211 """
212 # print("END", tag)
213 if check_already_closed and tag in self.already_closed_empty_element:
214 # This is a redundant end tag for an empty-element tag.
215 # We've already called handle_endtag() for it, so just
216 # check it off the list.
217 # print("ALREADY CLOSED", tag)
218 self.already_closed_empty_element.remove(tag)
219 else:
220 self.soup.handle_endtag(tag)
221
222 def handle_data(self, data: str) -> None:
223 """Handle some textual data that shows up between tags."""
224 self.soup.handle_data(data)
225
226 def handle_charref(self, name: str) -> None:
227 """Handle a numeric character reference by converting it to the
228 corresponding Unicode character and treating it as textual
229 data.
230
231 :param name: Character number, possibly in hexadecimal.
232 """
233 # TODO: This was originally a workaround for a bug in
234 # HTMLParser. (http://bugs.python.org/issue13633) The bug has
235 # been fixed, but removing this code still makes some
236 # Beautiful Soup tests fail. This needs investigation.
237 real_name:int
238 if name.startswith("x"):
239 real_name = int(name.lstrip("x"), 16)
240 elif name.startswith("X"):
241 real_name = int(name.lstrip("X"), 16)
242 else:
243 real_name = int(name)
244
245 data, replacement_added = UnicodeDammit.numeric_character_reference(real_name)
246 if replacement_added:
247 self.soup.contains_replacement_characters = True
248 self.handle_data(data)
249
250 def handle_entityref(self, name: str) -> None:
251 """Handle a named entity reference by converting it to the
252 corresponding Unicode character(s) and treating it as textual
253 data.
254
255 :param name: Name of the entity reference.
256 """
257 character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name)
258 if character is not None:
259 data = character
260 else:
261 # If this were XML, it would be ambiguous whether "&foo"
262 # was an character entity reference with a missing
263 # semicolon or the literal string "&foo". Since this is
264 # HTML, we have a complete list of all character entity references,
265 # and this one wasn't found, so assume it's the literal string "&foo".
266 data = "&%s" % name
267 self.handle_data(data)
268
269 def handle_comment(self, data: str) -> None:
270 """Handle an HTML comment.
271
272 :param data: The text of the comment.
273 """
274 self.soup.endData()
275 self.soup.handle_data(data)
276 self.soup.endData(Comment)
277
278 def handle_decl(self, decl: str) -> None:
279 """Handle a DOCTYPE declaration.
280
281 :param data: The text of the declaration.
282 """
283 self.soup.endData()
284 decl = decl[len("DOCTYPE ") :]
285 self.soup.handle_data(decl)
286 self.soup.endData(Doctype)
287
288 def unknown_decl(self, data: str) -> None:
289 """Handle a declaration of unknown type -- probably a CDATA block.
290
291 :param data: The text of the declaration.
292 """
293 cls: Type[NavigableString]
294 if data.upper().startswith("CDATA["):
295 cls = CData
296 data = data[len("CDATA[") :]
297 else:
298 cls = Declaration
299 self.soup.endData()
300 self.soup.handle_data(data)
301 self.soup.endData(cls)
302
303 def handle_pi(self, data: str) -> None:
304 """Handle a processing instruction.
305
306 :param data: The text of the instruction.
307 """
308 self.soup.endData()
309 self.soup.handle_data(data)
310 self._document_might_be_xml(data)
311 self.soup.endData(ProcessingInstruction)
312
313
314class HTMLParserTreeBuilder(HTMLTreeBuilder):
315 """A Beautiful soup `bs4.builder.TreeBuilder` that uses the
316 :py:class:`html.parser.HTMLParser` parser, found in the Python
317 standard library.
318
319 """
320
321 is_xml: bool = False
322 picklable: bool = True
323 NAME: str = HTMLPARSER
324 features: Iterable[str] = [NAME, HTML, STRICT]
325 parser_args: Tuple[Iterable[Any], Dict[str, Any]]
326
327 #: The html.parser knows which line number and position in the
328 #: original file is the source of an element.
329 TRACKS_LINE_NUMBERS: bool = True
330
331 def __init__(
332 self,
333 parser_args: Optional[Iterable[Any]] = None,
334 parser_kwargs: Optional[Dict[str, Any]] = None,
335 **kwargs: Any,
336 ):
337 """Constructor.
338
339 :param parser_args: Positional arguments to pass into
340 the BeautifulSoupHTMLParser constructor, once it's
341 invoked.
342 :param parser_kwargs: Keyword arguments to pass into
343 the BeautifulSoupHTMLParser constructor, once it's
344 invoked.
345 :param kwargs: Keyword arguments for the superclass constructor.
346 """
347 # Some keyword arguments will be pulled out of kwargs and placed
348 # into parser_kwargs.
349 extra_parser_kwargs = dict()
350 for arg in ("on_duplicate_attribute",):
351 if arg in kwargs:
352 value = kwargs.pop(arg)
353 extra_parser_kwargs[arg] = value
354 super(HTMLParserTreeBuilder, self).__init__(**kwargs)
355 parser_args = parser_args or []
356 parser_kwargs = parser_kwargs or {}
357 parser_kwargs.update(extra_parser_kwargs)
358 parser_kwargs["convert_charrefs"] = False
359 self.parser_args = (parser_args, parser_kwargs)
360
361 def prepare_markup(
362 self,
363 markup: _RawMarkup,
364 user_specified_encoding: Optional[_Encoding] = None,
365 document_declared_encoding: Optional[_Encoding] = None,
366 exclude_encodings: Optional[_Encodings] = None,
367 ) -> Iterable[Tuple[str, Optional[_Encoding], Optional[_Encoding], bool]]:
368 """Run any preliminary steps necessary to make incoming markup
369 acceptable to the parser.
370
371 :param markup: Some markup -- probably a bytestring.
372 :param user_specified_encoding: The user asked to try this encoding.
373 :param document_declared_encoding: The markup itself claims to be
374 in this encoding.
375 :param exclude_encodings: The user asked _not_ to try any of
376 these encodings.
377
378 :yield: A series of 4-tuples: (markup, encoding, declared encoding,
379 has undergone character replacement)
380
381 Each 4-tuple represents a strategy for parsing the document.
382 This TreeBuilder uses Unicode, Dammit to convert the markup
383 into Unicode, so the ``markup`` element of the tuple will
384 always be a string.
385 """
386 if isinstance(markup, str):
387 # Parse Unicode as-is.
388 yield (markup, None, None, False)
389 return
390
391 # Ask UnicodeDammit to sniff the most likely encoding.
392
393 known_definite_encodings: List[_Encoding] = []
394 if user_specified_encoding:
395 # This was provided by the end-user; treat it as a known
396 # definite encoding per the algorithm laid out in the
397 # HTML5 spec. (See the EncodingDetector class for
398 # details.)
399 known_definite_encodings.append(user_specified_encoding)
400
401 user_encodings: List[_Encoding] = []
402 if document_declared_encoding:
403 # This was found in the document; treat it as a slightly
404 # lower-priority user encoding.
405 user_encodings.append(document_declared_encoding)
406
407 dammit = UnicodeDammit(
408 markup,
409 known_definite_encodings=known_definite_encodings,
410 user_encodings=user_encodings,
411 is_html=True,
412 exclude_encodings=exclude_encodings,
413 )
414
415 if dammit.unicode_markup is None:
416 # In every case I've seen, Unicode, Dammit is able to
417 # convert the markup into Unicode, even if it needs to use
418 # REPLACEMENT CHARACTER. But there is a code path that
419 # could result in unicode_markup being None, and
420 # HTMLParser can only parse Unicode, so here we handle
421 # that code path.
422 raise ParserRejectedMarkup(
423 "Could not convert input to Unicode, and html.parser will not accept bytestrings."
424 )
425 else:
426 yield (
427 dammit.unicode_markup,
428 dammit.original_encoding,
429 dammit.declared_html_encoding,
430 dammit.contains_replacement_characters,
431 )
432
433 def feed(self, markup: _RawMarkup, _parser_class:type[BeautifulSoupHTMLParser] =BeautifulSoupHTMLParser) -> None:
434 """
435 :param markup: The markup to feed into the parser.
436 :param _parser_class: An HTMLParser subclass to use. This is only intended for use in unit tests.
437 """
438 args, kwargs = self.parser_args
439
440 # HTMLParser.feed will only handle str, but
441 # BeautifulSoup.markup is allowed to be _RawMarkup, because
442 # it's set by the yield value of
443 # TreeBuilder.prepare_markup. Fortunately,
444 # HTMLParserTreeBuilder.prepare_markup always yields a str
445 # (UnicodeDammit.unicode_markup).
446 assert isinstance(markup, str)
447
448 # We know BeautifulSoup calls TreeBuilder.initialize_soup
449 # before calling feed(), so we can assume self.soup
450 # is set.
451 assert self.soup is not None
452 parser = _parser_class(self.soup, *args, **kwargs)
453
454 try:
455 parser.feed(markup)
456 parser.close()
457 except AssertionError as e:
458 # html.parser raises AssertionError in rare cases to
459 # indicate a fatal problem with the markup, especially
460 # when there's an error in the doctype declaration.
461 raise ParserRejectedMarkup(e)
462 parser.already_closed_empty_element = []