Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/bs4/builder/_htmlparser.py: 72%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

172 statements  

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 

13import re 

14 

15from typing import ( 

16 Any, 

17 Callable, 

18 cast, 

19 Dict, 

20 Iterable, 

21 List, 

22 Optional, 

23 TYPE_CHECKING, 

24 Tuple, 

25 Type, 

26 Union, 

27) 

28 

29from bs4.element import ( 

30 AttributeDict, 

31 CData, 

32 Comment, 

33 Declaration, 

34 Doctype, 

35 ProcessingInstruction, 

36) 

37from bs4.dammit import EntitySubstitution, UnicodeDammit 

38 

39from bs4.builder import ( 

40 DetectsXMLParsedAsHTML, 

41 HTML, 

42 HTMLTreeBuilder, 

43 STRICT, 

44) 

45 

46from bs4.exceptions import ParserRejectedMarkup 

47 

48if TYPE_CHECKING: 

49 from bs4 import BeautifulSoup 

50 from bs4.element import NavigableString 

51 from bs4._typing import ( 

52 _Encoding, 

53 _Encodings, 

54 _RawMarkup, 

55 ) 

56 

57HTMLPARSER = "html.parser" 

58 

59_DuplicateAttributeHandler = Callable[[Dict[str, str], str, str], None] 

60 

61 

62class BeautifulSoupHTMLParser(HTMLParser, DetectsXMLParsedAsHTML): 

63 #: Constant to handle duplicate attributes by ignoring later values 

64 #: and keeping the earlier ones. 

65 REPLACE: str = "replace" 

66 

67 #: Constant to handle duplicate attributes by replacing earlier values 

68 #: with later ones. 

69 IGNORE: str = "ignore" 

70 

71 """A subclass of the Python standard library's HTMLParser class, which 

72 listens for HTMLParser events and translates them into calls 

73 to Beautiful Soup's tree construction API. 

74 

75 :param on_duplicate_attribute: A strategy for what to do if a 

76 tag includes the same attribute more than once. Accepted 

77 values are: REPLACE (replace earlier values with later 

78 ones, the default), IGNORE (keep the earliest value 

79 encountered), or a callable. A callable must take three 

80 arguments: the dictionary of attributes already processed, 

81 the name of the duplicate attribute, and the most recent value 

82 encountered. 

83 """ 

84 

85 def __init__( 

86 self, 

87 soup: BeautifulSoup, 

88 *args: Any, 

89 on_duplicate_attribute: Union[str, _DuplicateAttributeHandler] = REPLACE, 

90 **kwargs: Any, 

91 ): 

92 self.soup = soup 

93 self.on_duplicate_attribute = on_duplicate_attribute 

94 self.attribute_dict_class = soup.builder.attribute_dict_class 

95 HTMLParser.__init__(self, *args, **kwargs) 

96 

97 # Keep a list of empty-element tags that were encountered 

98 # without an explicit closing tag. If we encounter a closing tag 

99 # of this type, we'll associate it with one of those entries. 

100 # 

101 # This isn't a stack because we don't care about the 

102 # order. It's a list of closing tags we've already handled and 

103 # will ignore, assuming they ever show up. 

104 self.already_closed_empty_element = [] 

105 

106 self._initialize_xml_detector() 

107 

108 on_duplicate_attribute: Union[str, _DuplicateAttributeHandler] 

109 already_closed_empty_element: List[str] 

110 soup: BeautifulSoup 

111 

112 def error(self, message: str) -> None: 

113 # NOTE: This method is required so long as Python 3.9 is 

114 # supported. The corresponding code is removed from HTMLParser 

115 # in 3.5, but not removed from ParserBase until 3.10. 

116 # https://github.com/python/cpython/issues/76025 

117 # 

118 # The original implementation turned the error into a warning, 

119 # but in every case I discovered, this made HTMLParser 

120 # immediately crash with an error message that was less 

121 # helpful than the warning. The new implementation makes it 

122 # more clear that html.parser just can't parse this 

123 # markup. The 3.10 implementation does the same, though it 

124 # raises AssertionError rather than calling a method. (We 

125 # catch this error and wrap it in a ParserRejectedMarkup.) 

126 raise ParserRejectedMarkup(message) 

127 

128 def handle_startendtag( 

129 self, tag: str, attrs: List[Tuple[str, Optional[str]]] 

130 ) -> None: 

131 """Handle an incoming empty-element tag. 

132 

133 html.parser only calls this method when the markup looks like 

134 <tag/>. 

135 """ 

136 # `handle_empty_element` tells handle_starttag not to close the tag 

137 # just because its name matches a known empty-element tag. We 

138 # know that this is an empty-element tag, and we want to call 

139 # handle_endtag ourselves. 

140 self.handle_starttag(tag, attrs, handle_empty_element=False) 

141 self.handle_endtag(tag) 

142 

143 def handle_starttag( 

144 self, 

145 tag: str, 

146 attrs: List[Tuple[str, Optional[str]]], 

147 handle_empty_element: bool = True, 

148 ) -> None: 

149 """Handle an opening tag, e.g. '<tag>' 

150 

151 :param handle_empty_element: True if this tag is known to be 

152 an empty-element tag (i.e. there is not expected to be any 

153 closing tag). 

154 """ 

155 # TODO: handle namespaces here? 

156 attr_dict: AttributeDict = self.attribute_dict_class() 

157 for key, value in attrs: 

158 # Change None attribute values to the empty string 

159 # for consistency with the other tree builders. 

160 if value is None: 

161 value = "" 

162 if key in attr_dict: 

163 # A single attribute shows up multiple times in this 

164 # tag. How to handle it depends on the 

165 # on_duplicate_attribute setting. 

166 on_dupe = self.on_duplicate_attribute 

167 if on_dupe == self.IGNORE: 

168 pass 

169 elif on_dupe in (None, self.REPLACE): 

170 attr_dict[key] = value 

171 else: 

172 on_dupe = cast(_DuplicateAttributeHandler, on_dupe) 

173 on_dupe(attr_dict, key, value) 

174 else: 

175 attr_dict[key] = value 

176 # print("START", tag) 

177 sourceline: Optional[int] 

178 sourcepos: Optional[int] 

179 if self.soup.builder.store_line_numbers: 

180 sourceline, sourcepos = self.getpos() 

181 else: 

182 sourceline = sourcepos = None 

183 tagObj = self.soup.handle_starttag( 

184 tag, None, None, attr_dict, sourceline=sourceline, sourcepos=sourcepos 

185 ) 

186 if tagObj is not None and tagObj.is_empty_element and handle_empty_element: 

187 # Unlike other parsers, html.parser doesn't send separate end tag 

188 # events for empty-element tags. (It's handled in 

189 # handle_startendtag, but only if the original markup looked like 

190 # <tag/>.) 

191 # 

192 # So we need to call handle_endtag() ourselves. Since we 

193 # know the start event is identical to the end event, we 

194 # don't want handle_endtag() to cross off any previous end 

195 # events for tags of this name. 

196 self.handle_endtag(tag, check_already_closed=False) 

197 

198 # But we might encounter an explicit closing tag for this tag 

199 # later on. If so, we want to ignore it. 

200 self.already_closed_empty_element.append(tag) 

201 

202 if self._root_tag_name is None: 

203 self._root_tag_encountered(tag) 

204 

205 def handle_endtag(self, tag: str, check_already_closed: bool = True) -> None: 

206 """Handle a closing tag, e.g. '</tag>' 

207 

208 :param tag: A tag name. 

209 :param check_already_closed: True if this tag is expected to 

210 be the closing portion of an empty-element tag, 

211 e.g. '<tag></tag>'. 

212 """ 

213 # print("END", tag) 

214 if check_already_closed and tag in self.already_closed_empty_element: 

215 # This is a redundant end tag for an empty-element tag. 

216 # We've already called handle_endtag() for it, so just 

217 # check it off the list. 

218 # print("ALREADY CLOSED", tag) 

219 self.already_closed_empty_element.remove(tag) 

220 else: 

221 self.soup.handle_endtag(tag) 

222 

223 def handle_data(self, data: str) -> None: 

224 """Handle some textual data that shows up between tags.""" 

225 self.soup.handle_data(data) 

226 

227 _DECIMAL_REFERENCE_WITH_FOLLOWING_DATA = re.compile("^([0-9]+)(.*)") 

228 _HEX_REFERENCE_WITH_FOLLOWING_DATA = re.compile("^([0-9a-f]+)(.*)") 

229 

230 @classmethod 

231 def _dereference_numeric_character_reference(cls, name:str) -> Tuple[str, bool, str]: 

232 """Convert a numeric character reference into an actual character. 

233 

234 :param name: The number of the character reference, as 

235 obtained by html.parser 

236 

237 :return: A 3-tuple (dereferenced, replacement_added, 

238 extra_data). `dereferenced` is the dereferenced character 

239 reference, or the empty string if there was no 

240 reference. `replacement_added` is True if the reference 

241 could only be dereferenced by replacing content with U+FFFD 

242 REPLACEMENT CHARACTER. `extra_data` is a portion of data 

243 following the character reference, which was deemed to be 

244 normal data and not part of the reference at all. 

245 """ 

246 dereferenced:str = "" 

247 replacement_added:bool = False 

248 extra_data:str = "" 

249 

250 base:int = 10 

251 reg = cls._DECIMAL_REFERENCE_WITH_FOLLOWING_DATA 

252 if name.startswith("x") or name.startswith("X"): 

253 # Hex reference 

254 name = name[1:] 

255 base = 16 

256 reg = cls._HEX_REFERENCE_WITH_FOLLOWING_DATA 

257 

258 real_name:Optional[int] = None 

259 try: 

260 real_name = int(name, base) 

261 except ValueError: 

262 # This is either bad data that starts with what looks like 

263 # a numeric character reference, or a real numeric 

264 # reference that wasn't terminated by a semicolon. 

265 # 

266 # The fix to https://bugs.python.org/issue13633 made it 

267 # our responsibility to handle the extra data. 

268 # 

269 # To preserve the old behavior, we extract the numeric 

270 # portion of the incoming "reference" and treat that as a 

271 # numeric reference. All subsequent data will be processed 

272 # as string data. 

273 match = reg.search(name) 

274 if match is not None: 

275 real_name = int(match.groups()[0], base) 

276 extra_data = match.groups()[1] 

277 

278 if real_name is None: 

279 dereferenced = "" 

280 extra_data = name 

281 else: 

282 dereferenced, replacement_added = UnicodeDammit.numeric_character_reference(real_name) 

283 return dereferenced, replacement_added, extra_data 

284 

285 def handle_charref(self, name: str) -> None: 

286 """Handle a numeric character reference by converting it to the 

287 corresponding Unicode character and treating it as textual 

288 data. 

289 

290 :param name: Character number, possibly in hexadecimal. 

291 """ 

292 dereferenced, replacement_added, extra_data = self._dereference_numeric_character_reference(name) 

293 if replacement_added: 

294 self.soup.contains_replacement_characters = True 

295 if dereferenced is not None: 

296 self.handle_data(dereferenced) 

297 if extra_data is not None: 

298 self.handle_data(extra_data) 

299 

300 def handle_entityref(self, name: str) -> None: 

301 """Handle a named entity reference by converting it to the 

302 corresponding Unicode character(s) and treating it as textual 

303 data. 

304 

305 :param name: Name of the entity reference. 

306 """ 

307 character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name) 

308 if character is not None: 

309 data = character 

310 else: 

311 # If this were XML, it would be ambiguous whether "&foo" 

312 # was an character entity reference with a missing 

313 # semicolon or the literal string "&foo". Since this is 

314 # HTML, we have a complete list of all character entity references, 

315 # and this one wasn't found, so assume it's the literal string "&foo". 

316 data = "&%s" % name 

317 self.handle_data(data) 

318 

319 def handle_comment(self, data: str) -> None: 

320 """Handle an HTML comment. 

321 

322 :param data: The text of the comment. 

323 """ 

324 self.soup.endData() 

325 self.soup.handle_data(data) 

326 self.soup.endData(Comment) 

327 

328 def handle_decl(self, decl: str) -> None: 

329 """Handle a DOCTYPE declaration. 

330 

331 :param data: The text of the declaration. 

332 """ 

333 self.soup.endData() 

334 decl = decl[len("DOCTYPE ") :] 

335 self.soup.handle_data(decl) 

336 self.soup.endData(Doctype) 

337 

338 def unknown_decl(self, data: str) -> None: 

339 """Handle a declaration of unknown type -- probably a CDATA block. 

340 

341 :param data: The text of the declaration. 

342 """ 

343 cls: Type[NavigableString] 

344 if data.upper().startswith("CDATA["): 

345 cls = CData 

346 data = data[len("CDATA[") :] 

347 else: 

348 cls = Declaration 

349 self.soup.endData() 

350 self.soup.handle_data(data) 

351 self.soup.endData(cls) 

352 

353 def handle_pi(self, data: str) -> None: 

354 """Handle a processing instruction. 

355 

356 :param data: The text of the instruction. 

357 """ 

358 self.soup.endData() 

359 self.soup.handle_data(data) 

360 self._document_might_be_xml(data) 

361 self.soup.endData(ProcessingInstruction) 

362 

363 

364class HTMLParserTreeBuilder(HTMLTreeBuilder): 

365 """A Beautiful soup `bs4.builder.TreeBuilder` that uses the 

366 :py:class:`html.parser.HTMLParser` parser, found in the Python 

367 standard library. 

368 

369 """ 

370 

371 is_xml: bool = False 

372 picklable: bool = True 

373 NAME: str = HTMLPARSER 

374 features: Iterable[str] = [NAME, HTML, STRICT] 

375 parser_args: Tuple[Iterable[Any], Dict[str, Any]] 

376 

377 #: The html.parser knows which line number and position in the 

378 #: original file is the source of an element. 

379 TRACKS_LINE_NUMBERS: bool = True 

380 

381 def __init__( 

382 self, 

383 parser_args: Optional[Iterable[Any]] = None, 

384 parser_kwargs: Optional[Dict[str, Any]] = None, 

385 **kwargs: Any, 

386 ): 

387 """Constructor. 

388 

389 :param parser_args: Positional arguments to pass into 

390 the BeautifulSoupHTMLParser constructor, once it's 

391 invoked. 

392 :param parser_kwargs: Keyword arguments to pass into 

393 the BeautifulSoupHTMLParser constructor, once it's 

394 invoked. 

395 :param kwargs: Keyword arguments for the superclass constructor. 

396 """ 

397 # Some keyword arguments will be pulled out of kwargs and placed 

398 # into parser_kwargs. 

399 extra_parser_kwargs = dict() 

400 for arg in ("on_duplicate_attribute",): 

401 if arg in kwargs: 

402 value = kwargs.pop(arg) 

403 extra_parser_kwargs[arg] = value 

404 super(HTMLParserTreeBuilder, self).__init__(**kwargs) 

405 parser_args = parser_args or [] 

406 parser_kwargs = parser_kwargs or {} 

407 parser_kwargs.update(extra_parser_kwargs) 

408 parser_kwargs["convert_charrefs"] = False 

409 self.parser_args = (parser_args, parser_kwargs) 

410 

411 def prepare_markup( 

412 self, 

413 markup: _RawMarkup, 

414 user_specified_encoding: Optional[_Encoding] = None, 

415 document_declared_encoding: Optional[_Encoding] = None, 

416 exclude_encodings: Optional[_Encodings] = None, 

417 ) -> Iterable[Tuple[str, Optional[_Encoding], Optional[_Encoding], bool]]: 

418 """Run any preliminary steps necessary to make incoming markup 

419 acceptable to the parser. 

420 

421 :param markup: Some markup -- probably a bytestring. 

422 :param user_specified_encoding: The user asked to try this encoding. 

423 :param document_declared_encoding: The markup itself claims to be 

424 in this encoding. 

425 :param exclude_encodings: The user asked _not_ to try any of 

426 these encodings. 

427 

428 :yield: A series of 4-tuples: (markup, encoding, declared encoding, 

429 has undergone character replacement) 

430 

431 Each 4-tuple represents a strategy for parsing the document. 

432 This TreeBuilder uses Unicode, Dammit to convert the markup 

433 into Unicode, so the ``markup`` element of the tuple will 

434 always be a string. 

435 """ 

436 if isinstance(markup, str): 

437 # Parse Unicode as-is. 

438 yield (markup, None, None, False) 

439 return 

440 

441 # Ask UnicodeDammit to sniff the most likely encoding. 

442 

443 known_definite_encodings: List[_Encoding] = [] 

444 if user_specified_encoding: 

445 # This was provided by the end-user; treat it as a known 

446 # definite encoding per the algorithm laid out in the 

447 # HTML5 spec. (See the EncodingDetector class for 

448 # details.) 

449 known_definite_encodings.append(user_specified_encoding) 

450 

451 user_encodings: List[_Encoding] = [] 

452 if document_declared_encoding: 

453 # This was found in the document; treat it as a slightly 

454 # lower-priority user encoding. 

455 user_encodings.append(document_declared_encoding) 

456 

457 dammit = UnicodeDammit( 

458 markup, 

459 known_definite_encodings=known_definite_encodings, 

460 user_encodings=user_encodings, 

461 is_html=True, 

462 exclude_encodings=exclude_encodings, 

463 ) 

464 

465 if dammit.unicode_markup is None: 

466 # In every case I've seen, Unicode, Dammit is able to 

467 # convert the markup into Unicode, even if it needs to use 

468 # REPLACEMENT CHARACTER. But there is a code path that 

469 # could result in unicode_markup being None, and 

470 # HTMLParser can only parse Unicode, so here we handle 

471 # that code path. 

472 raise ParserRejectedMarkup( 

473 "Could not convert input to Unicode, and html.parser will not accept bytestrings." 

474 ) 

475 else: 

476 yield ( 

477 dammit.unicode_markup, 

478 dammit.original_encoding, 

479 dammit.declared_html_encoding, 

480 dammit.contains_replacement_characters, 

481 ) 

482 

483 def feed(self, markup: _RawMarkup, _parser_class:type[BeautifulSoupHTMLParser] =BeautifulSoupHTMLParser) -> None: 

484 """ 

485 :param markup: The markup to feed into the parser. 

486 :param _parser_class: An HTMLParser subclass to use. This is only intended for use in unit tests. 

487 """ 

488 args, kwargs = self.parser_args 

489 

490 # HTMLParser.feed will only handle str, but 

491 # BeautifulSoup.markup is allowed to be _RawMarkup, because 

492 # it's set by the yield value of 

493 # TreeBuilder.prepare_markup. Fortunately, 

494 # HTMLParserTreeBuilder.prepare_markup always yields a str 

495 # (UnicodeDammit.unicode_markup). 

496 assert isinstance(markup, str) 

497 

498 # We know BeautifulSoup calls TreeBuilder.initialize_soup 

499 # before calling feed(), so we can assume self.soup 

500 # is set. 

501 assert self.soup is not None 

502 parser = _parser_class(self.soup, *args, **kwargs) 

503 

504 try: 

505 parser.feed(markup) 

506 parser.close() 

507 except AssertionError as e: 

508 # html.parser raises AssertionError in rare cases to 

509 # indicate a fatal problem with the markup, especially 

510 # when there's an error in the doctype declaration. 

511 raise ParserRejectedMarkup(e) 

512 parser.already_closed_empty_element = []