"""HTML loader based on Python's standard-library HTML parser."""
import re
from html.parser import HTMLParser
from typing import ClassVar
from langchain_core.documents import Document
from .base import BaseFileLoader
class _VisibleTextParser(HTMLParser):
"""Collect visible text while excluding non-content HTML elements."""
_IGNORED_TAGS: ClassVar[set[str]] = {"script", "style", "noscript", "svg"}
_BLOCK_TAGS: ClassVar[set[str]] = {
"address",
"article",
"blockquote",
"br",
"dd",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"li",
"main",
"nav",
"ol",
"p",
"section",
"table",
"tr",
"ul",
}
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self._ignored_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in self._IGNORED_TAGS:
self._ignored_depth += 1
elif not self._ignored_depth and tag in self._BLOCK_TAGS:
self.parts.append("\n")
def handle_endtag(self, tag: str) -> None:
if tag in self._IGNORED_TAGS and self._ignored_depth:
self._ignored_depth -= 1
elif not self._ignored_depth and tag in self._BLOCK_TAGS:
self.parts.append("\n")
def handle_data(self, data: str) -> None:
if not self._ignored_depth and data.strip():
self.parts.append(data)
[docs]
class HTMLFileLoader(BaseFileLoader):
"""Extract readable text from HTML without an external parser dependency."""
[docs]
def load(self) -> list[Document]:
"""Parse HTML and return its visible text as one document."""
try:
html = self.file_path.read_text(
encoding=self.kwargs.get("encoding", "utf-8")
)
parser = _VisibleTextParser()
parser.feed(html)
parser.close()
except (OSError, UnicodeError, ValueError) as exc:
raise RuntimeError(
f"Failed to load HTML file {self.file_path}: {exc}"
) from exc
content = "".join(parser.parts)
content = re.sub(r"[ \t]+", " ", content)
content = re.sub(r"\n\s*\n\s*\n+", "\n\n", content).strip()
return [
Document(page_content=content, metadata={"source": str(self.file_path)})
]
[docs]
@staticmethod
def get_install_command() -> str:
"""Return the installation command for this built-in loader."""
return "No additional dependencies required."