在Node.js中使用代理(Axios + Puppeteer + SDK)

学习如何与Axios,Puppeteer,Playwright,以及ProxyHat SDK在Node.js中配置代理. 包括旋转、地理瞄准、重试和同时刮刮的代码示例.

在Node.js中使用代理(Axios + Puppeteer + SDK)

为什么在Node.js中使用代理?

节点(Node.js)是最受欢迎的运行时间之一,用于建造网络刮刮器,API集成器,以及自动化工具. 但是,如果你从一个IP地址发送上百或上千个请求,你将很快会遇到利率限制,CAPTCHA,以及彻底的IP禁令. 节点中的代理 解决这个问题的方法是通过不同的IP地址来引导您的请求,使每个请求看起来都来自一个独特的用户.

无论是在刮掉产品价格,监测搜索引擎排名,还是大规模收集公共数据,代理都是必不可少的基础设施. 在本指南中,我们将涵盖所有你需要的将住宅代理纳入你的节点.js项目。 代理节点 SDKAxios, Puppeteer, 和 Playwright. (英语).

如果您仍在评估哪个代理类型适合您的使用大小写, 请检查我们的比较 住宅对数据中心对移动代理。 。 。

安装和设置

安装代理Hat SDK

最快的开始方式是官方的节点SDK. 它处理验证,旋转,和连接集合出框:

npm install proxyhat

您还想要您计划使用的 HTTP 客户端 :

npm install axios puppeteer playwright

认证

所有代理连接通过您的 API 认证 。 您可以在 代理哈特仪表板。SDK作为构建器选项或环境变量接受:

// Option 1: Pass credentials directly
const ProxyHat = require('proxyhat');
const client = new ProxyHat({
  username: 'your_username',
  password: 'your_password',
});
// Option 2: Use environment variables
// Set PROXYHAT_USERNAME and PROXYHAT_PASSWORD in your .env
const client = new ProxyHat();

简单 请求 SDK

SDK提供高级 fetch 自动处理代理旋转的方法 :

const ProxyHat = require('proxyhat');
const client = new ProxyHat();
async function main() {
  const response = await client.fetch('https://httpbin.org/ip', {
    country: 'us',
  });
  console.log('Status:', response.status);
  console.log('Body:', await response.text());
}
main().catch(console.error);

每个调用自动选择不同的住宅IP. 不需要手动代理 URL 格式化 。

使用带有 Axios 的代理

Axios是Node.js生态系统中最受欢迎的HTTP客户端. 要将 Axios 请求通过 ProxyHat 路径,您可以直接使用 SDK 的代理 URL 或配置 Axios 。

方法1: SDK 代理代理

const ProxyHat = require('proxyhat');
const axios = require('axios');
const client = new ProxyHat();
const agent = client.createAgent({ country: 'us' });
async function scrapeWithAxios() {
  const response = await axios.get('https://httpbin.org/ip', {
    httpAgent: agent,
    httpsAgent: agent,
    timeout: 30000,
  });
  console.log('IP:', response.data.origin);
}
scrapeWithAxios();

方法2:直接代理 URL

如果您更喜欢手动配置, 请使用标准代理 URL 格式与 https-proxy-agent 软件包 :

const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const proxyUrl = 'http://USERNAME:PASSWORD@gate.proxyhat.com:8080';
const agent = new HttpsProxyAgent(proxyUrl);
async function scrapeWithAxios() {
  const response = await axios.get('https://httpbin.org/ip', {
    httpsAgent: agent,
    timeout: 30000,
  });
  console.log('IP:', response.data.origin);
}
scrapeWithAxios();

带有默认代理的 Axios 实例

对于重复使用,创建预配置的 Axios 实例 :

const { HttpsProxyAgent } = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://USERNAME:PASSWORD@gate.proxyhat.com:8080');
const proxyClient = axios.create({
  httpsAgent: agent,
  timeout: 30000,
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  },
});
// All requests now go through the proxy
const res = await proxyClient.get('https://example.com');

使用带有 Puppeteer 的代理

Puppeteer推出一个无头Chrome浏览器,这是刮掉JavaScript-havy网站的理想. 代理配置在浏览器发布级别.

const puppeteer = require('puppeteer');
async function scrapeWithPuppeteer() {
  const browser = await puppeteer.launch({
    args: ['--proxy-server=gate.proxyhat.com:8080'],
    headless: 'new',
  });
  const page = await browser.newPage();
  // Authenticate with the proxy
  await page.authenticate({
    username: 'USERNAME',
    password: 'PASSWORD',
  });
  await page.goto('https://httpbin.org/ip', {
    waitUntil: 'networkidle2',
    timeout: 60000,
  });
  const content = await page.evaluate(() => document.body.innerText);
  console.log('IP:', content);
  await browser.close();
}
scrapeWithPuppeteer();

带有地理目标的傀儡

要针对特定国家,请在您的用户名中加入国家代码。 代理服务器使用格式 USERNAME-country-XX编号 :

await page.authenticate({
  username: 'USERNAME-country-de',  // Route through Germany
  password: 'PASSWORD',
});

浏览我们所有可用的代理地址 地点页面。 。 。

使用带有 Playwright 的代理

Playwright支持Chrimium,Firefox,和WebKit. 星洲网. 代理配置被构建在发射选项中,使其更加简单:

const { chromium } = require('playwright');
async function scrapeWithPlaywright() {
  const browser = await chromium.launch({
    proxy: {
      server: 'http://gate.proxyhat.com:8080',
      username: 'USERNAME',
      password: 'PASSWORD',
    },
  });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://httpbin.org/ip');
  const body = await page.textContent('body');
  console.log('IP:', body);
  await browser.close();
}
scrapeWithPlaywright();

带有 per- Context 代理 的 Playwright

Playwright 每个浏览器上下文允许不同的代理,这对多账户或多区域刮切有用:

const browser = await chromium.launch();
// US context
const usContext = await browser.newContext({
  proxy: {
    server: 'http://gate.proxyhat.com:8080',
    username: 'USERNAME-country-us',
    password: 'PASSWORD',
  },
});
// UK context
const ukContext = await browser.newContext({
  proxy: {
    server: 'http://gate.proxyhat.com:8080',
    username: 'USERNAME-country-gb',
    password: 'PASSWORD',
  },
});
const usPage = await usContext.newPage();
const ukPage = await ukContext.newPage();
await Promise.all([
  usPage.goto('https://www.google.com/search?q=proxy+service'),
  ukPage.goto('https://www.google.co.uk/search?q=proxy+service'),
]);

旋转对粘性会话

代理Hat支持满足不同刮切需求的两种会话模式:

特性旋转粘着
每个请求的IP每次新建 IP会话持续时间相同 IP
最佳办法大规模刮刮多步骤工作流程、登录会话
会期不详最多30分钟
用户名格式USERNAMEUSERNAME-session-XXXX

粘贴会话示例

const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios');
// Generate a random session ID
const sessionId = 'session_' + Math.random().toString(36).slice(2, 10);
const agent = new HttpsProxyAgent(
  `http://USERNAME-session-${sessionId}:PASSWORD@gate.proxyhat.com:8080`
);
// All requests with this agent use the same IP
const client = axios.create({ httpsAgent: agent, timeout: 30000 });
const res1 = await client.get('https://httpbin.org/ip');
const res2 = await client.get('https://httpbin.org/ip');
console.log(res1.data.origin === res2.data.origin); // true

地理目标请求

地理目标对于 SERP 跟踪、当地价格监测以及区域内容核查。 PoxyHat 通过您的用户名字符串支持国家级别和城市级别的目标:

// Country targeting
const countryAgent = new HttpsProxyAgent(
  'http://USERNAME-country-jp:PASSWORD@gate.proxyhat.com:8080'
);
// City targeting
const cityAgent = new HttpsProxyAgent(
  'http://USERNAME-country-us-city-newyork:PASSWORD@gate.proxyhat.com:8080'
);

请检查date=中的日期值 (帮助) 可用地点 支助国家和城市。

处理和检索错误

网络错误在规模化与代理合作时是不可避免的. 强有力的再试验战略对废品生产至关重要:

const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
async function fetchWithRetry(url, options = {}) {
  const maxRetries = options.maxRetries || 3;
  const baseDelay = options.baseDelay || 1000;
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const agent = new HttpsProxyAgent(
        'http://USERNAME:PASSWORD@gate.proxyhat.com:8080'
      );
      const response = await axios.get(url, {
        httpsAgent: agent,
        timeout: options.timeout || 30000,
      });
      if (response.status === 200) return response;
      throw new Error(`HTTP ${response.status}`);
    } catch (error) {
      console.warn(`Attempt ${attempt}/${maxRetries} failed: ${error.message}`);
      if (attempt === maxRetries) throw error;
      // Exponential backoff: 1s, 2s, 4s...
      const delay = baseDelay * Math.pow(2, attempt - 1);
      await new Promise(r => setTimeout(r, delay));
    }
  }
}
// Usage
const response = await fetchWithRetry('https://example.com', {
  maxRetries: 3,
  timeout: 20000,
});

与货币控制同步擦拭

立即发送所有请求 Promise.all 可以覆盖你的机器和目标服务器。 使用货币限制器控制并行连接的数目 :

async function asyncPool(concurrency, items, iteratorFn) {
  const results = [];
  const executing = new Set();
  for (const [index, item] of items.entries()) {
    const promise = Promise.resolve().then(() => iteratorFn(item, index));
    results.push(promise);
    executing.add(promise);
    const cleanup = () => executing.delete(promise);
    promise.then(cleanup, cleanup);
    if (executing.size >= concurrency) {
      await Promise.race(executing);
    }
  }
  return Promise.all(results);
}
// Scrape 100 URLs, 10 at a time
const urls = Array.from({ length: 100 }, (_, i) =>
  `https://example.com/page/${i + 1}`
);
const results = await asyncPool(10, urls, async (url) => {
  return fetchWithRetry(url, { maxRetries: 2, timeout: 15000 });
});

用于大型 网络刮除项目在速度和可靠性之间保持了良好的平衡。 阅读我们的指南 2026年网络刮刮的最佳代理 更多的建筑建议。

制作提示

连接管理

  • 重复使用 Axios 实例和代理代理代理,而不是每个请求创建新的代理代理代理 。 这样可以避免套接字耗尽。
  • 设定 keepAlive: true 在您的 HTTP 代理中持续连接 。
  • 使用后迅速关闭Pippeteer/Playwright浏览器以释放内存.

内存和超时

  • 对于傀儡,使用 page.setRequestInterception(true) 当您只需要 HTML 内容时,可以屏蔽图像、 CSS 和字体。 这大大降低了带宽和内存的使用.
  • 总是为每个请求设定明确的超时. 缺时是吊刮器的头号原因。
  • 监视节点.js内存 process.memoryUsage() 在长期刮刮机。

请求截取更快的搜索

const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', (req) => {
  const blocked = ['image', 'stylesheet', 'font', 'media'];
  if (blocked.includes(req.resourceType())) {
    req.abort();
  } else {
    req.continue();
  }
});
await page.goto('https://example.com');

环境变量

从来没有硬码证书。 使用一个 .env 文件并装入 dotenv编号 :

require('dotenv').config();
const proxyUrl = `http://${process.env.PROXY_USER}:${process.env.PROXY_PASS}@gate.proxyhat.com:8080`;

准备好了吗? 检查 我们的定价计划 以找到您工程的适量住宅代理带宽。

关键外卖

  • 这个 代理节点 SDK 是添加代理支持的最快方式。 安装方式 npm install proxyhat 并开始以三行代码获取。
  • 轴线 通过 https-proxy-agent 或者SDK的内置代理。 创建可重复使用的 Axios 实例以提高效率 。
  • 傀儡 接受代理作为发射参数。 调用 page.authenticate() 通过全权证书。
  • 剧作家 在其启动和上下文选项中拥有本地代理支持,包括多区域拆解的内文本代理。
  • 使用 粘贴会议 多步骤工作流程和 旋转 IP 用于大规模数据收集。
  • 总是执行 用指数反转重试逻辑货币控制 在生产废料。
  • 在无头浏览器中屏蔽不必要的资源以减少带宽和提高速度.

准备开始了吗?

通过AI过滤访问148多个国家的5000多万个住宅IP。

查看价格住宅代理
← 返回博客