|
| 1 | +from html.parser import HTMLParser |
| 2 | + |
| 3 | + |
| 4 | +class HTMLValidator: |
| 5 | + """Check whether HTML content is well-formed, i.e. every tag has a matching close tag. |
| 6 | +
|
| 7 | + This only verifies tag balance/nesting via a streaming `html.parser.HTMLParser`, not |
| 8 | + conformance to the actual HTML5 element vocabulary or content model — unknown tag names |
| 9 | + (e.g. `<foobar>`) are accepted as well-formed as long as they're properly closed. |
| 10 | + """ |
| 11 | + |
| 12 | + @staticmethod |
| 13 | + def validate_html(path: str) -> bool: |
| 14 | + """Return True if the file at `path` is well-formed HTML, False otherwise. |
| 15 | +
|
| 16 | + Reads and parses the file in chunks so memory use stays bounded regardless of file size. |
| 17 | + """ |
| 18 | + parser = TagChecker() |
| 19 | + |
| 20 | + try: |
| 21 | + with open(path, "r", encoding="utf-8") as f: |
| 22 | + while chunk := f.read(64000): |
| 23 | + parser.feed(chunk) |
| 24 | + parser.close() |
| 25 | + except FileNotFoundError as e: |
| 26 | + raise e |
| 27 | + except ValueError: |
| 28 | + return False |
| 29 | + |
| 30 | + return parser.tag_stack == [] |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def validate_string(string: str) -> bool: |
| 34 | + """Return True if `string` is well-formed HTML, False otherwise.""" |
| 35 | + parser = TagChecker() |
| 36 | + |
| 37 | + try: |
| 38 | + parser.feed(string) |
| 39 | + parser.close() |
| 40 | + except ValueError: |
| 41 | + return False |
| 42 | + return parser.tag_stack == [] |
| 43 | + |
| 44 | + |
| 45 | +class TagChecker(HTMLParser): |
| 46 | + """Tracks open tags on a stack, raising ValueError on any mismatched or unclosed tag.""" |
| 47 | + |
| 48 | + def __init__(self): |
| 49 | + super().__init__() |
| 50 | + self.tag_stack = [] |
| 51 | + |
| 52 | + def handle_starttag(self, tag, attrs): |
| 53 | + self.tag_stack.append(tag) |
| 54 | + |
| 55 | + def handle_endtag(self, tag): |
| 56 | + if not self.tag_stack or self.tag_stack[-1] != tag: |
| 57 | + raise ValueError(f"Mismatched end tag: {tag}") |
| 58 | + self.tag_stack.pop() |
| 59 | + |
| 60 | + def close(self): |
| 61 | + """Flush any buffered data, then raise ValueError if any tags were left unclosed.""" |
| 62 | + super().close() |
| 63 | + if self.tag_stack: |
| 64 | + raise ValueError(f"Unclosed tags: {self.tag_stack}") |
0 commit comments