Spaces:
Sleeping
Sleeping
Download scraper.py from Ramasani/WebScrapper-AI: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/Ramasani/WebScrapper-AI/resolve/main/scraper.py
- Command line
-
hf download hf://spaces/Ramasani/WebScrapper-AI/scraper.py
-
curl -L -o scraper.py https://huggingface.co/spaces/Ramasani/WebScrapper-AI/resolve/main/scraper.py
11 kB
| import asyncio | |
| from typing import List, Dict, Any, Optional | |
| from bs4 import BeautifulSoup | |
| from playwright.async_api import async_playwright, Browser, BrowserContext, Page | |
| import logging | |
| from config import config | |
| logger = logging.getLogger(__name__) | |
| class BrowserPool: | |
| _instance = None | |
| _lock = asyncio.Lock() | |
| def __new__(cls): | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| cls._instance._initialized = False | |
| return cls._instance | |
| def __init__(self): | |
| if self._initialized: | |
| return | |
| self.browser: Optional[Browser] = None | |
| self.context: Optional[BrowserContext] = None | |
| self.semaphore: Optional[asyncio.Semaphore] = None | |
| self._page_count = 0 | |
| self._initialized = True | |
| async def initialize(self): | |
| if self.browser is not None: | |
| return | |
| self.semaphore = asyncio.Semaphore(config.max_concurrent_pages) | |
| self.playwright = await async_playwright().start() | |
| launch_args = [ | |
| "--no-sandbox", | |
| "--disable-setuid-sandbox", | |
| "--disable-dev-shm-usage", | |
| "--disable-accelerated-2d-canvas", | |
| "--no-first-run", | |
| "--no-zygote", | |
| "--disable-gpu", | |
| "--single-process", | |
| "--disable-features=VizDisplayCompositor,TranslateUI,BlinkGenPropertyTrees", | |
| "--disable-background-timer-throttling", | |
| "--disable-backgrounding-occluded-windows", | |
| "--disable-renderer-backgrounding", | |
| "--disable-ipc-flooding-protection", | |
| "--memory-pressure-off", | |
| "--max_old_space_size=1024", | |
| ] | |
| self.browser = await self.playwright.chromium.launch( | |
| headless=config.headless, | |
| args=launch_args | |
| ) | |
| self.context = await self.browser.new_context( | |
| viewport={"width": 1280, "height": 720}, | |
| user_agent=config.user_agent, | |
| java_script_enabled=True, | |
| bypass_csp=True, | |
| ignore_https_errors=True, | |
| ) | |
| if config.block_resources: | |
| await self.context.route("**/*", self._block_resources) | |
| logger.info("Browser pool initialized") | |
| async def _block_resources(self, route, request): | |
| blocked_types = {"image", "font", "stylesheet", "media", "websocket", "manifest"} | |
| if request.resource_type in blocked_types: | |
| await route.abort() | |
| else: | |
| await route.continue_() | |
| async def get_page(self) -> Page: | |
| if self.browser is None or self.context is None: | |
| await self.initialize() | |
| await self.semaphore.acquire() | |
| self._page_count += 1 | |
| page = await self.context.new_page() | |
| page.set_default_timeout(config.request_timeout) | |
| page.set_default_navigation_timeout(config.request_timeout) | |
| original_close = page.close | |
| async def tracked_close(*args, **kwargs): | |
| self._page_count -= 1 | |
| self.semaphore.release() | |
| await original_close(*args, **kwargs) | |
| page.close = tracked_close | |
| return page | |
| async def close(self): | |
| if self.context: | |
| await self.context.close() | |
| if self.browser: | |
| await self.browser.close() | |
| if hasattr(self, 'playwright'): | |
| await self.playwright.stop() | |
| self.browser = None | |
| self.context = None | |
| logger.info("Browser pool closed") | |
| browser_pool = BrowserPool() | |
| def extract_page_data(html: str, url: str) -> Dict[str, Any]: | |
| soup = BeautifulSoup(html, "lxml") | |
| title = "" | |
| if soup.title and soup.title.string: | |
| title = soup.title.string.strip() | |
| metadata = { | |
| "url": url, | |
| "title": title, | |
| "description": "", | |
| "keywords": "", | |
| "author": "", | |
| "og:title": "", | |
| "og:description": "", | |
| "og:image": "", | |
| "og:url": "", | |
| "og:type": "", | |
| "twitter:card": "", | |
| "twitter:title": "", | |
| "twitter:description": "", | |
| "twitter:image": "", | |
| "canonical": "", | |
| "robots": "", | |
| "viewpoint": "" | |
| } | |
| for tag in soup.find_all("meta"): | |
| name = (tag.get("name") or tag.get("property") or "").lower() | |
| content = tag.get("content", "") | |
| if name in metadata: | |
| metadata[name] = content | |
| link_tag = soup.find("link", rel="canonical") | |
| if link_tag: | |
| metadata["canonical"] = link_tag.get("href", "") | |
| viewport = soup.find("meta", attrs={"name": "viewport"}) | |
| if viewport: | |
| metadata["viewpoint"] = viewport.get("content", "") | |
| robots = soup.find("meta", attrs={"name": "robots"}) | |
| if robots: | |
| metadata["robots"] = robots.get("content", "") | |
| body = soup.find("body") | |
| text = body.get_text(separator=" ", strip=True) if body else soup.get_text(separator=" ", strip=True) | |
| clean_text = " ".join(text.split()) | |
| markdown_parts = [] | |
| if title: | |
| markdown_parts.append(f"# {title}\n") | |
| if metadata["description"]: | |
| markdown_parts.append(f'> {metadata["description"]}\n') | |
| markdown_parts.append("\n## Content\n\n") | |
| content_block_tags = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "table", "blockquote", "img"] | |
| for tag in soup.find_all(content_block_tags): | |
| tag_name = tag.name | |
| if tag_name in ("h1", "h2", "h3", "h4", "h5", "h6"): | |
| level = int(tag_name[1]) | |
| prefix = "#" * level | |
| text = tag.get_text(strip=True) | |
| markdown_parts.append(f"{prefix} {text}\n\n") | |
| elif tag_name == "p": | |
| text = tag.get_text(strip=True) | |
| if text: | |
| markdown_parts.append(f"{text}\n\n") | |
| elif tag_name in ("ul", "ol"): | |
| for i, li in enumerate(tag.find_all("li", recursive=False)): | |
| prefix = "- " if tag_name == "ul" else f"{i + 1}. " | |
| text = li.get_text(strip=True) | |
| markdown_parts.append(f"{prefix}{text}\n") | |
| markdown_parts.append("\n") | |
| elif tag_name == "table": | |
| rows = tag.find_all("tr") | |
| if rows: | |
| headers = [th.get_text(strip=True) for th in rows[0].find_all(["th", "td"])] | |
| if headers: | |
| markdown_parts.append("| " + " | ".join(headers) + " |\n") | |
| markdown_parts.append("| " + " | ".join(["---"] * len(headers)) + " |\n") | |
| for row in rows[1:]: | |
| cells = [td.get_text(strip=True) for td in row.find_all(["td", "th"])] | |
| markdown_parts.append("| " + " | ".join(cells) + " |\n") | |
| markdown_parts.append("\n") | |
| elif tag_name == "blockquote": | |
| text = tag.get_text(strip=True) | |
| markdown_parts.append(f"> {text}\n\n") | |
| elif tag_name == "img": | |
| alt = tag.get("alt", "").strip() | |
| src = tag.get("src", "").strip() | |
| if alt: | |
| markdown_parts.append(f"\n\n") | |
| if not markdown_parts: | |
| markdown_parts.append(clean_text[:5000]) | |
| markdown = "".join(markdown_parts) | |
| links = [] | |
| for a in soup.find_all("a", href=True): | |
| href = a["href"].strip() | |
| if href and not href.startswith(("javascript:", "mailto:", "tel:", "#")): | |
| links.append(href) | |
| links = list(dict.fromkeys(links)) | |
| images = [] | |
| for img in soup.find_all("img", src=True): | |
| src = img["src"].strip() | |
| alt = img.get("alt", "").strip() | |
| if src: | |
| images.append({"src": src, "alt": alt}) | |
| images = [dict(t) for t in {tuple(d.items()) for d in images}] | |
| headings = [] | |
| for level in range(1, 7): | |
| for tag in soup.find_all(f"h{level}"): | |
| headings.append({ | |
| "level": level, | |
| "text": tag.get_text(strip=True) | |
| }) | |
| return { | |
| "clean_text": clean_text[:config.max_content_size] if len(clean_text) > config.max_content_size else clean_text, | |
| "markdown": markdown[:config.max_content_size] if len(markdown) > config.max_content_size else markdown, | |
| "metadata": metadata, | |
| "links": links[:1000], | |
| "images": images[:500], | |
| "headings": headings | |
| } | |
| async def scrape_url(url: str) -> Dict[str, Any]: | |
| page = await browser_pool.get_page() | |
| result = { | |
| "url": url, | |
| "html": None, | |
| "title": None, | |
| "status_code": None, | |
| "error": None, | |
| "clean_text": None, | |
| "markdown": None, | |
| "metadata": None, | |
| "links": None, | |
| "images": None, | |
| "headings": None, | |
| } | |
| try: | |
| response = await page.goto(url, wait_until="domcontentloaded", timeout=config.request_timeout) | |
| result["status_code"] = response.status if response else 0 | |
| if result["status_code"] >= 400: | |
| result["error"] = f"HTTP {result['status_code']}" | |
| return result | |
| await page.wait_for_load_state("networkidle", timeout=5000) | |
| result["title"] = await page.title() | |
| html = await page.content() | |
| if html: | |
| result["html"] = html[:config.max_content_size] if len(html) > config.max_content_size else html | |
| page_data = extract_page_data(html, url) | |
| result["title"] = page_data["metadata"]["title"] or result["title"] | |
| result["clean_text"] = page_data["clean_text"] | |
| result["markdown"] = page_data["markdown"] | |
| result["metadata"] = page_data["metadata"] | |
| result["links"] = page_data["links"] | |
| result["images"] = page_data["images"] | |
| result["headings"] = page_data["headings"] | |
| except asyncio.TimeoutError: | |
| result["error"] = "Timeout" | |
| except Exception as e: | |
| result["error"] = str(e) | |
| logger.error(f"Error scraping {url}: {e}") | |
| finally: | |
| await page.close() | |
| return result | |
| async def scrape_urls(urls: List[str]) -> List[Dict[str, Any]]: | |
| await browser_pool.initialize() | |
| semaphore = asyncio.Semaphore(config.max_concurrent_pages) | |
| async def scrape_with_semaphore(url: str): | |
| async with semaphore: | |
| return await scrape_url(url) | |
| tasks = [scrape_with_semaphore(url) for url in urls] | |
| results = await asyncio.gather(*tasks, return_exceptions=True) | |
| processed = [] | |
| for i, result in enumerate(results): | |
| if isinstance(result, Exception): | |
| processed.append({ | |
| "url": urls[i], | |
| "html": None, | |
| "title": None, | |
| "status_code": 0, | |
| "error": str(result), | |
| "clean_text": None, | |
| "markdown": None, | |
| "metadata": None, | |
| "links": None, | |
| "images": None, | |
| "headings": None, | |
| }) | |
| else: | |
| processed.append(result) | |
| return processed | |
| async def close_browser_pool(): | |
| await browser_pool.close() | |