| 1 | import re |
| 2 | import requests |
| 3 | from typing import Iterator |
| 4 | from bs4 import BeautifulSoup |
| 5 | from graphrag_sdk.document import Document |
| 6 | |
| 7 | |
| 8 | class HTMLLoader: |
| 9 | """ |
| 10 | Load HTML |
| 11 | """ |
| 12 | |
| 13 | def __init__(self, path: str) -> None: |
| 14 | """ |
| 15 | Initialize loader |
| 16 | |
| 17 | Parameters: |
| 18 | path (str): path to HTML. |
| 19 | """ |
| 20 | |
| 21 | self.path = path |
| 22 | |
| 23 | def _get_file(self) -> str: |
| 24 | try: |
| 25 | with open(self.path, "r") as f: |
| 26 | return f.read() |
| 27 | except requests.exceptions.RequestException as e: |
| 28 | print(f"An error occurred: {e}") |
| 29 | |
| 30 | def load(self) -> Iterator[Document]: |
| 31 | """ |
| 32 | Load HTML |
| 33 | |
| 34 | Returns: |
| 35 | Iterator[Document]: document iterator |
| 36 | """ |
| 37 | |
| 38 | # Download URL |
| 39 | content = self._get_file() |
| 40 | |
| 41 | # extract text from HTML, populate content |
| 42 | soup = BeautifulSoup(content, "html.parser") |
| 43 | |
| 44 | # Extract text from the HTML |
| 45 | content = soup.get_text() |
| 46 | |
| 47 | # Remove extra newlines |
| 48 | content = re.sub(r"\n{2,}", "\n", content) |
| 49 | |
| 50 | yield Document(content) |
| 51 | # return f"{self.source}\n{self.content}" |