| 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 | class URLLoader(): |
| 8 | """ |
| 9 | Load URL |
| 10 | """ |
| 11 | |
| 12 | def __init__(self, url: str) -> None: |
| 13 | """ |
| 14 | Initialize loader |
| 15 | |
| 16 | Parameters: |
| 17 | url (str): url. |
| 18 | """ |
| 19 | |
| 20 | self.url = url |
| 21 | |
| 22 | def _download(self) -> str: |
| 23 | try: |
| 24 | response = requests.get(self.url, headers={'User-Agent': 'Mozilla/5.0'}) |
| 25 | response.raise_for_status() # Raise an HTTPError for bad responses (4xx and 5xx) |
| 26 | return response.text |
| 27 | except requests.exceptions.RequestException as e: |
| 28 | print(f"An error occurred: {e}") |
| 29 | |
| 30 | def load(self) -> Iterator[Document]: |
| 31 | """ |
| 32 | Load URL |
| 33 | |
| 34 | Returns: |
| 35 | Iterator[Document]: document iterator |
| 36 | """ |
| 37 | |
| 38 | # Download URL |
| 39 | content = self._download() |
| 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}" |