Spaces:
Runtime error
Runtime error
File size: 7,946 Bytes
35b22df |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
"""Web scraper."""
import logging
from typing import Any, Callable, Dict, List, Optional, Tuple
import requests
from gpt_index.readers.base import BaseReader
from gpt_index.readers.schema.base import Document
class SimpleWebPageReader(BaseReader):
"""Simple web page reader.
Reads pages from the web.
Args:
html_to_text (bool): Whether to convert HTML to text.
Requires `html2text` package.
"""
def __init__(self, html_to_text: bool = False) -> None:
"""Initialize with parameters."""
try:
import html2text # noqa: F401
except ImportError:
raise ImportError(
"`html2text` package not found, please run `pip install html2text`"
)
self._html_to_text = html_to_text
def load_data(self, urls: List[str]) -> List[Document]:
"""Load data from the input directory.
Args:
urls (List[str]): List of URLs to scrape.
Returns:
List[Document]: List of documents.
"""
if not isinstance(urls, list):
raise ValueError("urls must be a list of strings.")
documents = []
for url in urls:
response = requests.get(url, headers=None).text
if self._html_to_text:
import html2text
response = html2text.html2text(response)
documents.append(Document(response))
return documents
class TrafilaturaWebReader(BaseReader):
"""Trafilatura web page reader.
Reads pages from the web.
Requires the `trafilatura` package.
"""
def __init__(self, error_on_missing: bool = False) -> None:
"""Initialize with parameters.
Args:
error_on_missing (bool): Throw an error when data cannot be parsed
"""
self.error_on_missing = error_on_missing
try:
import trafilatura # noqa: F401
except ImportError:
raise ImportError(
"`trafilatura` package not found, please run `pip install trafilatura`"
)
def load_data(self, urls: List[str]) -> List[Document]:
"""Load data from the urls.
Args:
urls (List[str]): List of URLs to scrape.
Returns:
List[Document]: List of documents.
"""
import trafilatura
if not isinstance(urls, list):
raise ValueError("urls must be a list of strings.")
documents = []
for url in urls:
downloaded = trafilatura.fetch_url(url)
if not downloaded:
if self.error_on_missing:
raise ValueError(f"Trafilatura fails to get string from url: {url}")
continue
response = trafilatura.extract(downloaded)
if not response:
if self.error_on_missing:
raise ValueError(f"Trafilatura fails to parse page: {url}")
continue
documents.append(Document(response))
return documents
def _substack_reader(soup: Any) -> Tuple[str, Dict[str, Any]]:
"""Extract text from Substack blog post."""
extra_info = {
"Title of this Substack post": soup.select_one("h1.post-title").getText(),
"Subtitle": soup.select_one("h3.subtitle").getText(),
"Author": soup.select_one("span.byline-names").getText(),
}
text = soup.select_one("div.available-content").getText()
return text, extra_info
DEFAULT_WEBSITE_EXTRACTOR: Dict[str, Callable[[Any], Tuple[str, Dict[str, Any]]]] = {
"substack.com": _substack_reader,
}
class BeautifulSoupWebReader(BaseReader):
"""BeautifulSoup web page reader.
Reads pages from the web.
Requires the `bs4` and `urllib` packages.
Args:
file_extractor (Optional[Dict[str, Callable]]): A mapping of website
hostname (e.g. google.com) to a function that specifies how to
extract text from the BeautifulSoup obj. See DEFAULT_WEBSITE_EXTRACTOR.
"""
def __init__(
self,
website_extractor: Optional[Dict[str, Callable]] = None,
) -> None:
"""Initialize with parameters."""
try:
from urllib.parse import urlparse # noqa: F401
import requests # noqa: F401
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
raise ImportError(
"`bs4`, `requests`, and `urllib` must be installed to scrape websites."
"Please run `pip install bs4 requests urllib`."
)
self.website_extractor = website_extractor or DEFAULT_WEBSITE_EXTRACTOR
def load_data(
self, urls: List[str], custom_hostname: Optional[str] = None
) -> List[Document]:
"""Load data from the urls.
Args:
urls (List[str]): List of URLs to scrape.
custom_hostname (Optional[str]): Force a certain hostname in the case
a website is displayed under custom URLs (e.g. Substack blogs)
Returns:
List[Document]: List of documents.
"""
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
documents = []
for url in urls:
try:
page = requests.get(url)
except Exception:
raise ValueError(f"One of the inputs is not a valid url: {url}")
hostname = custom_hostname or urlparse(url).hostname or ""
soup = BeautifulSoup(page.content, "html.parser")
data = ""
extra_info = {"URL": url}
if hostname in self.website_extractor:
data, metadata = self.website_extractor[hostname](soup)
extra_info.update(metadata)
else:
data = soup.getText()
documents.append(Document(data, extra_info=extra_info))
return documents
class RssReader(BaseReader):
"""RSS reader.
Reads content from an RSS feed.
"""
def __init__(self, html_to_text: bool = False) -> None:
"""Initialize with parameters.
Args:
html_to_text (bool): Whether to convert HTML to text.
Requires `html2text` package.
"""
try:
import feedparser # noqa: F401
except ImportError:
raise ImportError(
"`feedparser` package not found, please run `pip install feedparser`"
)
if html_to_text:
try:
import html2text # noqa: F401
except ImportError:
raise ImportError(
"`html2text` package not found, please run `pip install html2text`"
)
self._html_to_text = html_to_text
def load_data(self, urls: List[str]) -> List[Document]:
"""Load data from RSS feeds.
Args:
urls (List[str]): List of RSS URLs to load.
Returns:
List[Document]: List of documents.
"""
import feedparser
if not isinstance(urls, list):
raise ValueError("urls must be a list of strings.")
documents = []
for url in urls:
parsed = feedparser.parse(url)
for entry in parsed.entries:
if "content" in entry:
data = entry.content[0].value
else:
data = entry.description or entry.summary
if self._html_to_text:
import html2text
data = html2text.html2text(data)
extra_info = {"title": entry.title, "link": entry.link}
documents.append(Document(data, extra_info=extra_info))
return documents
if __name__ == "__main__":
reader = SimpleWebPageReader()
logging.info(reader.load_data(["http://www.google.com"]))
|