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
| import asyncio import aiohttp import weakref from contextlib import asynccontextmanager from typing import AsyncGenerator, Optional import logging
class OptimizedSpider: """优化后的爬虫实现""" def __init__(self, max_concurrent: int = 200): self.max_concurrent = max_concurrent self.semaphore = asyncio.Semaphore(max_concurrent) self.stats = { "processed_pages": 0, "failed_pages": 0, "current_memory_mb": 0 } @asynccontextmanager async def get_session(self) -> AsyncGenerator[aiohttp.ClientSession, None]: """会话上下文管理器""" connector = aiohttp.TCPConnector( limit=100, limit_per_host=20, ttl_dns_cache=300, use_dns_cache=True, ) timeout = aiohttp.ClientTimeout(total=30, connect=10) session = aiohttp.ClientSession( connector=connector, timeout=timeout ) try: yield session finally: await session.close() await asyncio.sleep(0.1) async def crawl_website(self, base_url: str, urls: List[str], callback=None) -> Dict: """爬取网站 - 优化版本""" async with self.get_session() as session: batch_size = 50 results = { "processed": 0, "failed": 0, "success": 0 } for i in range(0, len(urls), batch_size): batch_urls = urls[i:i + batch_size] batch_tasks = [] for url in batch_urls: task = self._crawl_page_optimized(session, url, callback) batch_tasks.append(task) batch_results = await asyncio.gather(*batch_tasks, return_exceptions=True) for result in batch_results: if isinstance(result, Exception): results["failed"] += 1 logging.error(f"批次处理异常: {result}") else: results["processed"] += 1 if result.get("success"): results["success"] += 1 del batch_tasks del batch_results gc.collect() self.stats["processed_pages"] += len(batch_urls) current_memory = psutil.Process().memory_info().rss / 1024 / 1024 self.stats["current_memory_mb"] = current_memory if i % (batch_size * 10) == 0: logging.info(f"处理进度: {i}/{len(urls)}, 内存使用: {current_memory:.1f}MB") return results async def _crawl_page_optimized(self, session: aiohttp.ClientSession, url: str, callback=None) -> Dict: """优化的页面爬取方法""" async with self.semaphore: try: async with session.get(url) as response: if response.status != 200: return {"url": url, "success": False, "error": f"HTTP {response.status}"} content = await response.text() parsed_data = await self._parse_page_lightweight(content) if callback: await callback(url, parsed_data) return { "url": url, "success": True, "content_length": len(content), "parsed_items": len(parsed_data) } except asyncio.TimeoutError: return {"url": url, "success": False, "error": "timeout"} except Exception as e: return {"url": url, "success": False, "error": str(e)} async def _parse_page_lightweight(self, content: str) -> List[Dict]: """轻量级页面解析""" try: from lxml import html tree = html.fromstring(content) products = [] product_elements = tree.xpath('//div[@class="product-item"]') for element in product_elements: try: product = { "title": element.xpath('.//h3/text()')[0] if element.xpath('.//h3/text()') else "", "price": element.xpath('.//span[@class="price"]/text()')[0] if element.xpath('.//span[@class="price"]/text()') else "", "link": element.xpath('.//a/@href')[0] if element.xpath('.//a/@href') else "" } if product["title"]: products.append(product) except Exception as e: logging.debug(f"解析产品元素失败: {e}") continue return products except ImportError: from bs4 import BeautifulSoup soup = BeautifulSoup(content, 'lxml') products = [] product_containers = soup.find_all('div', class_='product-item')[:50] for container in product_containers: try: title_elem = container.find('h3') price_elem = container.find('span', class_='price') link_elem = container.find('a') product = { "title": title_elem.get_text(strip=True) if title_elem else "", "price": price_elem.get_text(strip=True) if price_elem else "", "link": link_elem.get('href', '') if link_elem else "" } if product["title"]: products.append(product) except Exception as e: logging.debug(f"BeautifulSoup解析失败: {e}") continue del soup return products
async def save_data_callback(url: str, products: List[Dict]): """数据保存回调 - 流式处理""" if not products: return try: import aiofiles import json filename = f"data/{url.replace('/', '_').replace(':', '')}.json" async with aiofiles.open(filename, 'w', encoding='utf-8') as f: await f.write(json.dumps(products, ensure_ascii=False, indent=2)) logging.info(f"保存数据成功: {url}, 产品数: {len(products)}") except Exception as e: logging.error(f"保存数据失败: {url}, 错误: {e}")
|