|
| 1 | +# Copyright 2023 DeepL SE (https://www.deepl.com) |
| 2 | +# Use of this source code is governed by an MIT |
| 3 | +# license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +from html.parser import HTMLParser |
| 6 | +import html |
| 7 | +from typing import List, Tuple, Dict |
| 8 | + |
| 9 | + |
| 10 | +class PassthroughHTMLParser(HTMLParser): |
| 11 | + """ |
| 12 | + An HTML parser that accumulates parsed HTML in the original HTML. |
| 13 | + The original HTML can be accessed using parsed(). |
| 14 | +
|
| 15 | + Note: some HTML features are not correctly handled and reproduced: entity |
| 16 | + references, character references, declarations, processing instructions. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self): |
| 20 | + super().__init__(convert_charrefs=False) |
| 21 | + self._result = "" |
| 22 | + |
| 23 | + def parsed(self): |
| 24 | + return self._result |
| 25 | + |
| 26 | + def _append(self, text): |
| 27 | + self._result += text |
| 28 | + |
| 29 | + def handle_startendtag(self, tag, attrs): |
| 30 | + self._append(f"<{tag}{self._encode_attrs(attrs)} />") |
| 31 | + |
| 32 | + def handle_starttag(self, tag, attrs): |
| 33 | + self._append(f"<{tag}{self._encode_attrs(attrs)}>") |
| 34 | + |
| 35 | + def handle_endtag(self, tag): |
| 36 | + self._append(f"</{tag}>") |
| 37 | + |
| 38 | + def handle_charref(self, name): |
| 39 | + self._append(f"&#{name};") |
| 40 | + |
| 41 | + def handle_entityref(self, name): |
| 42 | + self._append(f"&{name};") |
| 43 | + |
| 44 | + def handle_data(self, data): |
| 45 | + self._append(data) |
| 46 | + |
| 47 | + def handle_comment(self, data): |
| 48 | + self._append(f"<!--{data}-->") |
| 49 | + |
| 50 | + def handle_decl(self, decl): |
| 51 | + self._append(f"<!{decl}>") |
| 52 | + |
| 53 | + def handle_pi(self, data): |
| 54 | + self._append(f"<?{data}>") |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def _encode_attrs(attrs: List[Tuple[str, str]]) -> str: |
| 58 | + if attrs: |
| 59 | + return " " + " ".join( |
| 60 | + f'{key}="{html.escape(value)}"' for key, value in attrs |
| 61 | + ) |
| 62 | + else: |
| 63 | + return "" |
| 64 | + |
| 65 | + |
| 66 | +class TagReplacerHTMLParser(PassthroughHTMLParser): |
| 67 | + """ |
| 68 | + An HTML parser that accumulates parsed HTML unmodified, except that |
| 69 | + matching start-end tags are replaced by prepared content. |
| 70 | +
|
| 71 | + :param replace_tags: A dictionary of tags to replace, with keys matching |
| 72 | + tag names ("tag") or tag names with IDs ("tag#id"), and values the text |
| 73 | + to replace matching tags with. |
| 74 | + """ |
| 75 | + |
| 76 | + def __init__(self, replace_tags: Dict[str, str]): |
| 77 | + super().__init__() |
| 78 | + self._replace_tags = replace_tags |
| 79 | + |
| 80 | + def handle_startendtag(self, tag, attrs): |
| 81 | + if self._replace_tag_if_matching(tag): |
| 82 | + return |
| 83 | + |
| 84 | + id = next((value for key, value in attrs if key == "id"), None) |
| 85 | + if id is not None and self._replace_tag_if_matching(f"{tag}#{id}"): |
| 86 | + return |
| 87 | + |
| 88 | + # If no replacement is found, fall back to passthrough parser |
| 89 | + super().handle_starttag(tag, attrs) |
| 90 | + |
| 91 | + def _replace_tag_if_matching(self, tag_and_id): |
| 92 | + if tag_and_id in self._replace_tags: |
| 93 | + stored_tag = self._replace_tags[tag_and_id] |
| 94 | + self._append(stored_tag) |
| 95 | + return True |
| 96 | + return False |
0 commit comments