[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-cn-daili-zhongjian-jian-ceng":3},{"success":4,"payload":5,"related":77,"errors":148},true,{"id":6,"slug":7,"title":8,"excerpt":9,"body_html":10,"meta_title":8,"meta_description":11,"canonical_url":12,"canonical_override":13,"og_title":8,"og_description":11,"og_image_url":14,"faq_json":15,"key_takeaways":31,"allow_index":37,"noindex_google_only":37,"allow_follow":4,"published_at":38,"updated_at":39,"content_updated_at":40,"featured_image_url":41,"featured_image_alt":13,"card_image_url":42,"reading_time_minutes":43,"author":44,"categories":48,"tags":55,"alternates":63,"locale_paths":75,"views":76},29,"daili-zhongjian-jian-ceng","构建爬虫代理中间件层","设计并构建生产级代理中件层,带有重试逻辑,故障,和度量衡. 在Python和Node.js中使用ProxyHat完成执行.","\u003Ch2>为什么要建立代理软件层\u003C\u002Fh2>\u003Cp>当您的刮切项目成长到单个脚本之外时, 您需要在您的应用程序代码和代理提供者之间有一个抽象层 。 一个中间软件层处理代理选择,认证,重试逻辑,故障,以及日志——所以你的刮子机只担心提取数据.\u003C\u002Fp>\u003Cp>没有中间软件,您的代码库中的每个刮子机都会重复代理配置,错误处理和旋转逻辑. 本指南向您演示如何在 Python 和 Node.js 中设计和构建一个生产级代理中件,使用 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fzuijia-wangluo-caiji-daili-2026\">代理哈特的住宅代理\u003C\u002Fa>。 。 。\u003C\u002Fp>\u003Cblockquote>代理软件位于您的应用程序和互联网之间。 它会拦截发出的请求,通过代理来引导请求,处理失败,并返回对您的应用程序代码的干净回复.\u003C\u002Fblockquote>\u003Ch2>结构概览\u003C\u002Fh2>\u003Cp>一个设计良好的代理中件有四个核心组件:\u003C\u002Fp>\u003Ctable>\n\u003Ccaption>结构概览\u003C\u002Fcaption>\u003Cthead>\u003Ctr>\u003Cth>构成部分\u003C\u002Fth>\u003Cth>责任\u003C\u002Fth>\u003Cth>为什么它很重要\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\u003Ctbody>\u003Ctr>\u003Ctd>代理管理器\u003C\u002Ftd>\u003Ctd>管理代理证书、会话和地理目标\u003C\u002Ftd>\u003Ctd>集中代理配置\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>请求拦截器\u003C\u002Ftd>\u003Ctd>用代理设置和信头环绕发送请求\u003C\u002Ftd>\u003Ctd>消除刮刮机中的锅炉板\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>重试引擎\u003C\u002Ftd>\u003Ctd>备份和代理旋转请求失败\u003C\u002Ftd>\u003Ctd>成功率从70%提高到95%\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>计量收集器\u003C\u002Ftd>\u003Ctd>跟踪间隔、成功率和错误模式\u003C\u002Ftd>\u003Ctd>启用数据驱动优化\u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftbody>\u003C\u002Ftable>\u003Ch2>Python 中件执行\u003C\u002Fh2>\u003Ch3>核心代理管理器\u003C\u002Fh3>\u003Cpre>\u003Ccode>import uuid\nimport time\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nlogger = logging.getLogger(__name__)\n@dataclass\nclass ProxyConfig:\n    gateway: str = \"gate.proxyhat.com\"\n    http_port: int = 8080\n    socks5_port: int = 1080\n    username: str = \"USERNAME\"\n    password: str = \"PASSWORD\"\n@dataclass\nclass RequestMetrics:\n    total: int = 0\n    success: int = 0\n    failed: int = 0\n    retries: int = 0\n    total_latency: float = 0.0\n    @property\n    def success_rate(self) -> float:\n        return (self.success \u002F self.total * 100) if self.total > 0 else 0.0\n    @property\n    def avg_latency(self) -> float:\n        return (self.total_latency \u002F self.success) if self.success > 0 else 0.0\nclass ProxyManager:\n    \"\"\"Manages proxy sessions, geo-targeting, and protocol selection.\"\"\"\n    def __init__(self, config: Optional[ProxyConfig] = None):\n        self.config = config or ProxyConfig()\n        self.metrics = RequestMetrics()\n    def get_proxy_url(\n        self,\n        protocol: str = \"http\",\n        country: Optional[str] = None,\n        session_id: Optional[str] = None,\n        sticky: bool = False,\n    ) -> str:\n        username = self.config.username\n        # Add session for sticky IPs\n        if sticky and not session_id:\n            session_id = uuid.uuid4().hex[:8]\n        if session_id:\n            username = f\"{username}-sid-{session_id}\"\n        # Add country targeting\n        if country:\n            username = f\"{username}-country-{country}\"\n        if protocol == \"socks5\":\n            port = self.config.socks5_port\n            scheme = \"socks5h\"\n        else:\n            port = self.config.http_port\n            scheme = \"http\"\n        return f\"{scheme}:\u002F\u002F{username}:{self.config.password}@{self.config.gateway}:{port}\"\n    def get_requests_proxies(self, **kwargs) -> dict:\n        \"\"\"Return a proxies dict compatible with the requests library.\"\"\"\n        url = self.get_proxy_url(**kwargs)\n        return {\"http\": url, \"https\": url}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch3>以备份重试引擎\u003C\u002Fh3>\u003Cpre>\u003Ccode>import requests\nfrom requests.exceptions import RequestException\nRETRYABLE_STATUS_CODES = {403, 429, 500, 502, 503, 504}\nclass RetryEngine:\n    \"\"\"Retries failed requests with exponential backoff and proxy rotation.\"\"\"\n    def __init__(\n        self,\n        proxy_manager: ProxyManager,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 30.0,\n        rotate_on_failure: bool = True,\n    ):\n        self.proxy_manager = proxy_manager\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self.rotate_on_failure = rotate_on_failure\n    def _should_retry(self, response: Optional[requests.Response], error: Optional[Exception]) -> bool:\n        if error:\n            return True\n        if response and response.status_code in RETRYABLE_STATUS_CODES:\n            return True\n        return False\n    def _get_delay(self, attempt: int) -> float:\n        delay = self.base_delay * (2 ** attempt)\n        return min(delay, self.max_delay)\n    def execute(\n        self,\n        method: str,\n        url: str,\n        country: Optional[str] = None,\n        sticky: bool = False,\n        **request_kwargs,\n    ) -> requests.Response:\n        session_id = uuid.uuid4().hex[:8] if sticky else None\n        last_error = None\n        for attempt in range(self.max_retries + 1):\n            # Rotate proxy on retry if enabled\n            if attempt > 0 and self.rotate_on_failure:\n                session_id = uuid.uuid4().hex[:8]\n                self.proxy_manager.metrics.retries += 1\n            proxies = self.proxy_manager.get_requests_proxies(\n                country=country, session_id=session_id\n            )\n            self.proxy_manager.metrics.total += 1\n            start_time = time.time()\n            try:\n                response = requests.request(\n                    method, url,\n                    proxies=proxies,\n                    timeout=request_kwargs.pop(\"timeout\", 30),\n                    **request_kwargs,\n                )\n                latency = time.time() - start_time\n                self.proxy_manager.metrics.total_latency += latency\n                if self._should_retry(response, None) and attempt \u003C self.max_retries:\n                    logger.warning(\n                        f\"Retryable status {response.status_code} for {url} \"\n                        f\"(attempt {attempt + 1}\u002F{self.max_retries + 1})\"\n                    )\n                    time.sleep(self._get_delay(attempt))\n                    continue\n                self.proxy_manager.metrics.success += 1\n                return response\n            except RequestException as e:\n                last_error = e\n                latency = time.time() - start_time\n                logger.error(f\"Request failed for {url}: {e} (attempt {attempt + 1})\")\n                if attempt \u003C self.max_retries:\n                    time.sleep(self._get_delay(attempt))\n                    continue\n                self.proxy_manager.metrics.failed += 1\n        raise last_error or Exception(f\"All retries exhausted for {url}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch3>完成中件类\u003C\u002Fh3>\u003Cpre>\u003Ccode>class ProxyMiddleware:\n    \"\"\"High-level middleware that wraps all proxy logic.\"\"\"\n    def __init__(\n        self,\n        config: Optional[ProxyConfig] = None,\n        max_retries: int = 3,\n        default_country: Optional[str] = None,\n    ):\n        self.proxy_manager = ProxyManager(config)\n        self.retry_engine = RetryEngine(\n            proxy_manager=self.proxy_manager,\n            max_retries=max_retries,\n        )\n        self.default_country = default_country\n        self.default_headers = {\n            \"Accept\": \"text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8\",\n            \"Accept-Language\": \"en-US,en;q=0.9\",\n            \"Accept-Encoding\": \"gzip, deflate, br\",\n        }\n    def get(self, url: str, **kwargs) -> requests.Response:\n        kwargs.setdefault(\"headers\", self.default_headers)\n        kwargs.setdefault(\"country\", self.default_country)\n        return self.retry_engine.execute(\"GET\", url, **kwargs)\n    def post(self, url: str, **kwargs) -> requests.Response:\n        kwargs.setdefault(\"headers\", self.default_headers)\n        kwargs.setdefault(\"country\", self.default_country)\n        return self.retry_engine.execute(\"POST\", url, **kwargs)\n    @property\n    def stats(self) -> dict:\n        m = self.proxy_manager.metrics\n        return {\n            \"total_requests\": m.total,\n            \"successful\": m.success,\n            \"failed\": m.failed,\n            \"retries\": m.retries,\n            \"success_rate\": f\"{m.success_rate:.1f}%\",\n            \"avg_latency\": f\"{m.avg_latency:.3f}s\",\n        }\n# Usage\nmiddleware = ProxyMiddleware(max_retries=3, default_country=\"us\")\n# Simple GET — all proxy logic is hidden\nresponse = middleware.get(\"https:\u002F\u002Fhttpbin.org\u002Fip\")\nprint(response.json())\n# Geo-targeted request\nresponse = middleware.get(\"https:\u002F\u002Fexample.com\u002Fpricing\", country=\"de\")\nprint(response.text[:200])\n# Check performance\nprint(middleware.stats)\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>节点.js 中件执行\u003C\u002Fh2>\u003Ch3>核心代理管理器\u003C\u002Fh3>\u003Cpre>\u003Ccode>const crypto = require('crypto');\nconst { HttpsProxyAgent } = require('https-proxy-agent');\nconst { SocksProxyAgent } = require('socks-proxy-agent');\nclass ProxyManager {\n  constructor(config = {}) {\n    this.gateway = config.gateway || 'gate.proxyhat.com';\n    this.httpPort = config.httpPort || 8080;\n    this.socks5Port = config.socks5Port || 1080;\n    this.username = config.username || 'USERNAME';\n    this.password = config.password || 'PASSWORD';\n    this.metrics = {\n      total: 0,\n      success: 0,\n      failed: 0,\n      retries: 0,\n      totalLatency: 0,\n    };\n  }\n  getProxyUrl({ protocol = 'http', country, sessionId, sticky = false } = {}) {\n    let username = this.username;\n    if (sticky && !sessionId) {\n      sessionId = crypto.randomBytes(4).toString('hex');\n    }\n    if (sessionId) username += `-sid-${sessionId}`;\n    if (country) username += `-country-${country}`;\n    const port = protocol === 'socks5' ? this.socks5Port : this.httpPort;\n    const scheme = protocol === 'socks5' ? 'socks5h' : 'http';\n    return `${scheme}:\u002F\u002F${username}:${this.password}@${this.gateway}:${port}`;\n  }\n  createAgent(options = {}) {\n    const url = this.getProxyUrl(options);\n    if (options.protocol === 'socks5') {\n      return new SocksProxyAgent(url);\n    }\n    return new HttpsProxyAgent(url);\n  }\n  get stats() {\n    const m = this.metrics;\n    return {\n      total: m.total,\n      success: m.success,\n      failed: m.failed,\n      retries: m.retries,\n      successRate: m.total > 0 ? ((m.success \u002F m.total) * 100).toFixed(1) + '%' : '0%',\n      avgLatency: m.success > 0 ? (m.totalLatency \u002F m.success).toFixed(3) + 's' : '0s',\n    };\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch3>重试引擎\u003C\u002Fh3>\u003Cpre>\u003Ccode>const RETRYABLE_STATUS_CODES = new Set([403, 429, 500, 502, 503, 504]);\nclass RetryEngine {\n  constructor(proxyManager, options = {}) {\n    this.proxyManager = proxyManager;\n    this.maxRetries = options.maxRetries || 3;\n    this.baseDelay = options.baseDelay || 1000;\n    this.maxDelay = options.maxDelay || 30000;\n    this.rotateOnFailure = options.rotateOnFailure !== false;\n  }\n  _getDelay(attempt) {\n    return Math.min(this.baseDelay * Math.pow(2, attempt), this.maxDelay);\n  }\n  _sleep(ms) {\n    return new Promise(resolve => setTimeout(resolve, ms));\n  }\n  async execute(url, options = {}) {\n    const { country, sticky, ...fetchOptions } = options;\n    let sessionId = sticky ? crypto.randomBytes(4).toString('hex') : undefined;\n    let lastError;\n    for (let attempt = 0; attempt \u003C= this.maxRetries; attempt++) {\n      if (attempt > 0 && this.rotateOnFailure) {\n        sessionId = crypto.randomBytes(4).toString('hex');\n        this.proxyManager.metrics.retries++;\n      }\n      const agent = this.proxyManager.createAgent({ country, sessionId });\n      this.proxyManager.metrics.total++;\n      const startTime = Date.now();\n      try {\n        const response = await fetch(url, {\n          ...fetchOptions,\n          agent,\n          signal: AbortSignal.timeout(fetchOptions.timeout || 30000),\n        });\n        const latency = (Date.now() - startTime) \u002F 1000;\n        this.proxyManager.metrics.totalLatency += latency;\n        if (RETRYABLE_STATUS_CODES.has(response.status) && attempt \u003C this.maxRetries) {\n          console.warn(\n            `Retryable status ${response.status} for ${url} ` +\n            `(attempt ${attempt + 1}\u002F${this.maxRetries + 1})`\n          );\n          await this._sleep(this._getDelay(attempt));\n          continue;\n        }\n        this.proxyManager.metrics.success++;\n        return response;\n      } catch (err) {\n        lastError = err;\n        console.error(`Request failed for ${url}: ${err.message} (attempt ${attempt + 1})`);\n        if (attempt \u003C this.maxRetries) {\n          await this._sleep(this._getDelay(attempt));\n          continue;\n        }\n        this.proxyManager.metrics.failed++;\n      }\n    }\n    throw lastError || new Error(`All retries exhausted for ${url}`);\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch3>完成中件类\u003C\u002Fh3>\u003Cpre>\u003Ccode>class ProxyMiddleware {\n  constructor(options = {}) {\n    this.proxyManager = new ProxyManager(options.proxy);\n    this.retryEngine = new RetryEngine(this.proxyManager, {\n      maxRetries: options.maxRetries || 3,\n    });\n    this.defaultCountry = options.defaultCountry || null;\n    this.defaultHeaders = {\n      'Accept': 'text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8',\n      'Accept-Language': 'en-US,en;q=0.9',\n      'User-Agent': 'Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36',\n    };\n  }\n  async get(url, options = {}) {\n    return this.retryEngine.execute(url, {\n      method: 'GET',\n      headers: { ...this.defaultHeaders, ...options.headers },\n      country: options.country || this.defaultCountry,\n      ...options,\n    });\n  }\n  async post(url, body, options = {}) {\n    return this.retryEngine.execute(url, {\n      method: 'POST',\n      headers: { ...this.defaultHeaders, ...options.headers },\n      body: typeof body === 'string' ? body : JSON.stringify(body),\n      country: options.country || this.defaultCountry,\n      ...options,\n    });\n  }\n  get stats() {\n    return this.proxyManager.stats;\n  }\n}\n\u002F\u002F Usage\nconst middleware = new ProxyMiddleware({\n  maxRetries: 3,\n  defaultCountry: 'us',\n});\n\u002F\u002F Simple GET\nconst response = await middleware.get('https:\u002F\u002Fhttpbin.org\u002Fip');\nconst data = await response.json();\nconsole.log(data);\n\u002F\u002F Check stats\nconsole.log(middleware.stats);\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>添加提供者失败\u003C\u002Fh2>\u003Cp>对于任务关键刮切,可以扩展中间软件,支持多个代理供应商自动故障.\u003C\u002Fp>\u003Cpre>\u003Ccode>class MultiProviderMiddleware:\n    \"\"\"Falls back to secondary proxy providers on failure.\"\"\"\n    def __init__(self, providers: list[ProxyConfig], max_retries: int = 3):\n        self.providers = [\n            ProxyMiddleware(config=cfg, max_retries=max_retries)\n            for cfg in providers\n        ]\n    def get(self, url: str, **kwargs) -> requests.Response:\n        last_error = None\n        for i, provider in enumerate(self.providers):\n            try:\n                response = provider.get(url, **kwargs)\n                if response.status_code \u003C 400:\n                    return response\n            except Exception as e:\n                last_error = e\n                logger.warning(f\"Provider {i} failed for {url}: {e}\")\n                continue\n        raise last_error or Exception(f\"All providers failed for {url}\")\n# Primary: ProxyHat | Fallback: backup provider\nproviders = [\n    ProxyConfig(\n        gateway=\"gate.proxyhat.com\",\n        username=\"USERNAME\",\n        password=\"PASSWORD\",\n    ),\n    ProxyConfig(\n        gateway=\"backup-proxy.example.com\",\n        username=\"BACKUP_USER\",\n        password=\"BACKUP_PASS\",\n    ),\n]\nmiddleware = MultiProviderMiddleware(providers)\nresponse = middleware.get(\"https:\u002F\u002Fexample.com\u002Fdata\")\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>Async Middle 软件( Python)\u003C\u002Fh2>\u003Cp>对于高通量刮刮,使用Aync版本,使用 \u003Ccode>aiohttp\u003C\u002Fcode>。关于更多的货币模式,请参见我们的指南。 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi\">用货币控制缩放代理请求\u003C\u002Fa>。 。 。\u003C\u002Fp>\u003Cpre>\u003Ccode>import aiohttp\nimport asyncio\nclass AsyncProxyMiddleware:\n    def __init__(self, config: Optional[ProxyConfig] = None, max_retries: int = 3):\n        self.proxy_manager = ProxyManager(config)\n        self.max_retries = max_retries\n    async def get(self, url: str, country: Optional[str] = None) -> str:\n        for attempt in range(self.max_retries + 1):\n            session_id = uuid.uuid4().hex[:8]\n            proxy_url = self.proxy_manager.get_proxy_url(\n                country=country, session_id=session_id\n            )\n            try:\n                async with aiohttp.ClientSession() as session:\n                    async with session.get(\n                        url, proxy=proxy_url, timeout=aiohttp.ClientTimeout(total=30)\n                    ) as response:\n                        if response.status in RETRYABLE_STATUS_CODES and attempt \u003C self.max_retries:\n                            await asyncio.sleep(2 ** attempt)\n                            continue\n                        self.proxy_manager.metrics.success += 1\n                        return await response.text()\n            except Exception as e:\n                if attempt == self.max_retries:\n                    self.proxy_manager.metrics.failed += 1\n                    raise\n                await asyncio.sleep(2 ** attempt)\n# Usage\nasync def main():\n    middleware = AsyncProxyMiddleware(max_retries=3)\n    urls = [f\"https:\u002F\u002Fexample.com\u002Fpage\u002F{i}\" for i in range(100)]\n    tasks = [middleware.get(url) for url in urls]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n    success = sum(1 for r in results if not isinstance(r, Exception))\n    print(f\"Success: {success}\u002F{len(results)}\")\n    print(middleware.proxy_manager.metrics)\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>与拼写框架相结合\u003C\u002Fh2>\u003Cp>中间器件与常见的刮刮图案清洁地融合. 这是如何用它与 Playwright 和标准的 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fpython-shiyong-daili\">Python 请求\u003C\u002Fa>。 。 。\u003C\u002Fp>\u003Cpre>\u003Ccode># With Playwright (Node.js)\nconst { chromium } = require('playwright');\nclass PlaywrightProxyMiddleware {\n  constructor(proxyManager) {\n    this.proxyManager = proxyManager;\n    this.browser = null;\n  }\n  async init() {\n    this.browser = await chromium.launch();\n  }\n  async scrape(url, options = {}) {\n    const proxyUrl = this.proxyManager.getProxyUrl({\n      sessionId: crypto.randomBytes(4).toString('hex'),\n      country: options.country,\n    });\n    const parsed = new URL(proxyUrl);\n    const context = await this.browser.newContext({\n      proxy: {\n        server: `${parsed.protocol}\u002F\u002F${parsed.hostname}:${parsed.port}`,\n        username: decodeURIComponent(parsed.username),\n        password: decodeURIComponent(parsed.password),\n      },\n    });\n    const page = await context.newPage();\n    try {\n      await page.goto(url, { timeout: 30000 });\n      return await page.content();\n    } finally {\n      await context.close();\n    }\n  }\n  async close() {\n    if (this.browser) await this.browser.close();\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>关于 Playwright 特定的代理模式,请参见我们 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fplaywright-lunhuan-daili\">Playwright 代理旋转指南\u003C\u002Fa>中件所收集的度量衡,请参见 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fjiankong-daili-xingneng\">监视代理性能\u003C\u002Fa>。 。 。\u003C\u002Fp>\u003Cp>探索 \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fpython-sdk\">Python SDK 键盘\u003C\u002Fa>, (中文). \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fnode-sdk\">节点 SDK\u003C\u002Fa>,或 \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\">冲啊 SDK\u003C\u002Fa> 用于内置中间软件特性,并检查 \u003Ca href=\"\u002Fcn\u002Fpricing\">代理用户定价\u003C\u002Fa> 开始吧 完整综合文件,访问 \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\">页面存档备份,存于互联网档案馆 docs.proxyhat.com\u003C\u002Fa>。 。 。\u003C\u002Fp>","为网络爬虫构建代理中间件层的完整指南。学习中间件设计模式、代理池管理、请求路由、错误处理和性能优化，提升爬虫系统的可靠性和效率。","\u002Fcn\u002Fblog\u002Fdaili-zhongjian-jian-ceng",null,"https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-og.webp",[16,19,22,25,28],{"question":17,"answer":18},"什么是代理中间件层？","代理中间件层是位于爬虫应用和代理服务之间的抽象层。它负责管理代理选择、请求路由、失败重试、IP轮换策略和性能监控。通过中间件，爬虫代码不需要直接处理代理逻辑，实现了关注点分离和更好的可维护性。",{"question":20,"answer":21},"为什么需要代理中间件而不是直接使用代理？","直接在每个请求中管理代理会导致代码重复、难以维护和扩展。中间件集中处理：根据目标自动选择代理类型、实现智能重试和故障转移、收集性能指标、管理请求速率限制和并发控制。这使得爬虫代码更简洁，代理策略更容易调整和优化。",{"question":23,"answer":24},"代理中间件应该包含哪些核心功能？","核心功能包括：代理池管理（健康检查、IP轮换）、请求路由（根据目标选择代理类型）、重试逻辑（指数退避、故障转移到不同代理）、速率限制（控制每IP和总体请求频率）、性能监控（成功率、延迟、带宽使用）和日志记录（调试和优化）。",{"question":26,"answer":27},"如何在中间件中实现智能代理选择？","建立目标网站到代理类型的映射表。受保护网站路由到住宅代理，无保护网站路由到数据中心代理。追踪每个代理在不同目标上的成功率，动态调整选择权重。实现回退机制：住宅代理失败时升级到移动代理。这种智能选择可以在保证成功率的同时优化成本。",{"question":29,"answer":30},"中间件如何处理代理失败？","实现分层重试策略：首先用不同IP重试（可能是临时IP封锁）、然后切换代理类型（从数据中心升级到住宅）、接着增加延迟重试（可能是速率限制）。记录失败原因用于分析和优化。将频繁失败的IP标记为冷却状态，避免浪费请求配额。",[32,33,34,35,36],"代理中间件层可以集中处理代理选择、认证、重试和指标收集，让爬虫代码只专注于数据提取。","设计良好的代理中间件包含代理管理器、请求拦截器、重试引擎和指标收集器四个核心组件。","重试引擎通过指数退避和代理轮换处理失败请求，可将成功率从70%提高到95%。","中间件支持在Python和Node.js中实现，并提供地理定位和粘性会话等实用功能。","对于关键任务，可以扩展中间件以支持多个代理提供商，并在失败时自动切换备用提供商。",false,"2026-02-02T07:15:32+00:00","2026-07-19T03:13:07+00:00","2026-10-03T08:21:32+00:00","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-card.webp",12,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[49],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},4,"kaifa-zhinan","开发者指南","开发者指南 | ProxyHat 博客","代码教程和SDK指南，帮助您将代理集成到应用程序中。",[56,60],{"id":57,"slug":58,"name":59},1,"web-scraping","网页抓取",{"id":43,"slug":61,"name":62},"sdk","SDK",{"pt":64,"ru":65,"zh":12,"de":66,"fr":67,"pl":68,"it":69,"es":70,"ja":71,"en":72,"tr":73,"ko":74,"x-default":72},"\u002Fpt\u002Fblog\u002Fcamada-middleware-de-proxy","\u002Fru\u002Fblog\u002Fsozdanie-promezhutochnogo-sloya-proksi","\u002Fde\u002Fblog\u002Fproxy-middleware-schicht-aufbauen","\u002Ffr\u002Fblog\u002Fconstruire-un-middleware-de-proxy","\u002Fpl\u002Fblog\u002Fbudowa-warstwa-proxy-middleware-do-skracania","\u002Fit\u002Fblog\u002Fcostruire-uno-strato-di-middleware-proxy-per-scraping","\u002Fes\u002Fblog\u002Fcapa-middleware-de-proxy-para-scraping","\u002Fja\u002Fblog\u002Fsukureipingu-no-tame-no-prokishi-midoruuea-reiyaa","\u002Fblog\u002Fproxy-middleware-layer","\u002Ftr\u002Fblog\u002Fscraping-icin-proxy-middleware-katmani","\u002Fko\u002Fblog\u002Fproxy-middleware-layer-guchuk",{"pt":64,"ru":65,"zh":12,"de":66,"fr":67,"pl":68,"it":69,"es":70,"ja":71,"en":72,"tr":73,"ko":74},45,[78,95,113,132],{"id":79,"slug":80,"title":81,"excerpt":82,"featured_image_url":83,"featured_image_alt":13,"card_image_url":84,"og_image_url":85,"published_at":86,"updated_at":39,"content_updated_at":87,"reading_time_minutes":43,"is_featured":37,"indexable":37,"views":88,"author":89,"categories":90,"tags":92},50,"sheji-kekaode-caiji-jiagou","设计可靠的网络爬虫架构","设计端到端的刮刮系统:排程器,URL队列,爬行器池,代理层,剖析器,存储,以及监控. 生产准备的 Python 代码与建筑图.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-og.webp","2026-02-24T06:55:16+00:00","2026-10-03T08:21:25+00:00",73,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[91],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[93,94],{"id":43,"slug":61,"name":62},{"id":57,"slug":58,"name":59},{"id":96,"slug":97,"title":98,"excerpt":99,"featured_image_url":100,"featured_image_alt":13,"card_image_url":101,"og_image_url":102,"published_at":103,"updated_at":39,"content_updated_at":104,"reading_time_minutes":105,"is_featured":37,"indexable":37,"views":106,"author":107,"categories":108,"tags":110},41,"jiankong-daili-xingneng","监控代理性能：延迟、成功率和告警","学习如何对代理性能进行仪表、监控和警报——跟踪延迟百分位数、成功率、错误模式和带宽。 Python、Node.js和Go的代码示例.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-og.webp","2026-02-15T00:39:23+00:00","2026-10-03T08:21:24+00:00",11,77,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[109],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[111,112],{"id":43,"slug":61,"name":62},{"id":57,"slug":58,"name":59},{"id":114,"slug":115,"title":116,"excerpt":117,"featured_image_url":118,"featured_image_alt":13,"card_image_url":119,"og_image_url":120,"published_at":121,"updated_at":39,"content_updated_at":122,"reading_time_minutes":123,"is_featured":37,"indexable":37,"views":79,"author":124,"categories":125,"tags":129},36,"kuozhan-caiji-jiagou","如何扩展网络爬虫基础设施","缩放网刮的架构模式:基于队列的系统,管道设计,带容器的横向缩放,以及规模化的代理管理. 代码在Python,Node.js,和去.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-og.webp","2026-02-09T14:42:34+00:00","2026-02-26T00:33:08+00:00",10,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[126],{"id":57,"slug":58,"name":59,"description":13,"meta_title":127,"meta_description":128,"parent_id":13},"网页抓取指南 | ProxyHat 博客","网页抓取技术、代理策略和数据提取最佳实践。",[130,131],{"id":57,"slug":58,"name":59},{"id":43,"slug":61,"name":62},{"id":133,"slug":134,"title":135,"excerpt":136,"featured_image_url":137,"featured_image_alt":13,"card_image_url":138,"og_image_url":139,"published_at":140,"updated_at":39,"content_updated_at":104,"reading_time_minutes":43,"is_featured":37,"indexable":37,"views":141,"author":142,"categories":143,"tags":145},35,"kuozhan-daili-qingqiu-bingfa-kongzhi","使用并发控制扩展代理请求","用于代理式刮刮的主货币图案:Ayncio semaphores,承诺池,Go工人池,限速器,以及反压. Python、Node.js和Go的生产代码.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-og.webp","2026-02-08T11:16:13+00:00",362,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[144],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[146,147],{"id":43,"slug":61,"name":62},{"id":57,"slug":58,"name":59},[]]