在网络爬取期间缓解 IP 禁令:针对遗留代码库的 TypeScript 方法

发布: (2026年2月3日 GMT+8 23:09)
5 min read
原文: Dev.to

I’m happy to translate the article for you, but I don’t see the article’s content in your message—only the source link. Could you please paste the text (or the portion you’d like translated) here? I’ll keep the source line, formatting, markdown, and code blocks exactly as you need.

Introduction

在网页抓取中,开发者和 QA 工程师经常面临的一个持续性挑战是 IP 地址被目标网站临时或永久封禁。这不仅会阻碍数据收集,还可能导致关键工作流中断。作为使用旧版 TypeScript 代码库的首席 QA 工程师,实施有效的策略以缓解 IP 封禁至关重要。本文探讨了实用技术,包括动态 IP 轮换和请求限速,专为旧系统量身定制。

理解问题

网站采用各种反爬虫手段,例如速率限制、IP 封禁和验证码。当在没有防护的情况下大量爬取时,服务器可能会阻止你的 IP,认为这是恶意行为。常见的做法是模拟人类行为、轮换 IP 并管理请求频率。

处理遗留 TypeScript 代码库中的 IP 封禁

虽然现代 SDK 和库提供了高级工具,但遗留的 TypeScript 项目通常仍依赖传统的 HTTP 请求框架,如 axioshttp。以下是在这些约束下的工作方式。

步骤 1:实现 IP 轮换

使用代理 IP 池。你可以维护一个代理服务器列表,并为每个请求随机选择一个。

const proxies = [
  { host: 'proxy1.example.com', port: 8080 },
  { host: 'proxy2.example.com', port: 8080 },
  { host: 'proxy3.example.com', port: 8080 },
];

function getRandomProxy() {
  const index = Math.floor(Math.random() * proxies.length);
  return proxies[index];
}

使用此函数为每个请求动态设置代理配置。

步骤 2:修改 HTTP 请求以使用代理

axios 中,你可以为每个请求指定代理:

import axios from 'axios';

async function fetchWithProxy(url: string) {
  const proxy = getRandomProxy();
  return axios.get(url, {
    proxy: {
      host: proxy.host,
      port: proxy.port,
    },
  });
}

// 使用示例
fetchWithProxy('https://targetwebsite.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

步骤 3:实现请求限流与随机延迟

为了模拟人类行为并避免触发速率限制,在请求之间加入随机延迟:

function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function scrapeData(urls: string[]) {
  for (const url of urls) {
    const delay = Math.random() * 3000 + 2000; // 2‑5 秒之间
    await sleep(delay);
    try {
      const response = await fetchWithProxy(url);
      console.log(`Fetched data from ${url}`);
      // 处理 response.data
    } catch (err) {
      console.error(`Error fetching ${url}:`, err);
    }
  }
}

Additional Best Practices

  • Rotate User‑Agents: 模拟不同的浏览器。
  • Use Headless Browsers: 用于应对复杂的反爬虫防御。
  • Monitor Response Codes: 检测封禁发生并暂时停止请求。
  • Limit Request Rate: 尊重服务器的限流策略。

结论

在传统的 TypeScript 代码库中处理 IP 封禁需要结合代理轮换、请求时机以及行为模拟。虽然这些方法可以显著降低被封禁的风险,但始终要确保你的爬取行为符合目标网站的服务条款。通过系统性地实施这些策略,质量保证团队可以维持更具弹性的爬取操作,确保数据流的连续性,同时不引起过多关注。

参考文献

QA 小贴士

专业提示: 使用 TempoMail USA 生成一次性测试账户。

Back to Blog

相关文章

阅读更多 »

TypeScript 或 泪水

前端质量门 另请参见:后端质量门 后端 linters 捕获 async footguns。Type checkers 防止 runtime explosions。现在轮到前端的……

Deno 沙盒

抱歉,我无法直接访问外部链接。请提供您想要翻译的具体摘录或摘要文本,我会为您翻译成简体中文。