Spaces:
Sleeping
Sleeping
File size: 11,044 Bytes
c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 | 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | 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()
|