|
| 1 | +import requests |
| 2 | +from bs4 import BeautifulSoup |
| 3 | +from urllib.parse import urljoin, urlparse |
| 4 | +from typing import Set, Dict, List |
| 5 | +import asyncio |
| 6 | +import aiohttp |
| 7 | +import logging |
| 8 | + |
| 9 | +class WebScraper: |
| 10 | + def __init__(self): |
| 11 | + self.visited_urls: Set[str] = set() |
| 12 | + self.max_depth = 3 |
| 13 | + self.max_pages = 100 |
| 14 | + self.timeout = 30 |
| 15 | + self.max_concurrent = 5 |
| 16 | + self.headers = { |
| 17 | + 'User-Agent': 'Rufus Bot 0.1 - AI-Powered Web Scraper for RAG Systems' |
| 18 | + } |
| 19 | + |
| 20 | + def should_crawl(self, url: str, base_domain: str) -> bool: |
| 21 | + if url in self.visited_urls: |
| 22 | + return False |
| 23 | + |
| 24 | + try: |
| 25 | + parsed = urlparse(url) |
| 26 | + if parsed.netloc != base_domain: |
| 27 | + return False |
| 28 | + |
| 29 | + skip_extensions = ('.pdf', '.jpg', '.png', '.gif', '.css', '.js') |
| 30 | + if any(url.lower().endswith(ext) for ext in skip_extensions): |
| 31 | + return False |
| 32 | + |
| 33 | + return True |
| 34 | + except: |
| 35 | + return False |
| 36 | + |
| 37 | + async def fetch_page(self, url: str, session: aiohttp.ClientSession) -> Dict: |
| 38 | + try: |
| 39 | + async with session.get(url, headers=self.headers) as response: |
| 40 | + if response.status == 200: |
| 41 | + html = await response.text() |
| 42 | + soup = BeautifulSoup(html, 'html.parser') |
| 43 | + |
| 44 | + for tag in soup(['script', 'style', 'meta', 'noscript']): |
| 45 | + tag.decompose() |
| 46 | + |
| 47 | + return { |
| 48 | + 'url': url, |
| 49 | + 'title': soup.title.string if soup.title else '', |
| 50 | + 'content': soup.get_text(separator=' ', strip=True), |
| 51 | + 'links': [ |
| 52 | + urljoin(url, link.get('href')) |
| 53 | + for link in soup.find_all('a', href=True) |
| 54 | + ] |
| 55 | + } |
| 56 | + return None |
| 57 | + except Exception as e: |
| 58 | + logging.error(f"Error fetching {url}: {str(e)}") |
| 59 | + return None |
| 60 | + |
| 61 | + async def crawl_async(self, start_url: str) -> List[Dict]: |
| 62 | + base_domain = urlparse(start_url).netloc |
| 63 | + to_visit = {start_url} |
| 64 | + results = [] |
| 65 | + |
| 66 | + connector = aiohttp.TCPConnector(limit=self.max_concurrent) |
| 67 | + timeout = aiohttp.ClientTimeout(total=self.timeout) |
| 68 | + |
| 69 | + async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session: |
| 70 | + while to_visit and len(self.visited_urls) < self.max_pages: |
| 71 | + current_batch = list(to_visit)[:self.max_concurrent] |
| 72 | + to_visit = set(list(to_visit)[self.max_concurrent:]) |
| 73 | + |
| 74 | + tasks = [ |
| 75 | + self.fetch_page(url, session) |
| 76 | + for url in current_batch |
| 77 | + if self.should_crawl(url, base_domain) |
| 78 | + ] |
| 79 | + |
| 80 | + pages = await asyncio.gather(*tasks, return_exceptions=True) |
| 81 | + |
| 82 | + for page in pages: |
| 83 | + if isinstance(page, dict): |
| 84 | + self.visited_urls.add(page['url']) |
| 85 | + results.append(page) |
| 86 | + for link in page.get('links', []): |
| 87 | + if self.should_crawl(link, base_domain): |
| 88 | + to_visit.add(link) |
| 89 | + |
| 90 | + return results |
| 91 | + |
| 92 | + def crawl(self, url: str) -> List[Dict]: |
| 93 | + return asyncio.run(self.crawl_async(url)) |
0 commit comments