Node.js에서 프록시 사용하기 (Axios + Puppeteer + SDK)

Node.js에서 프록시를 사용하는 방법을 알아봅니다. Axios, Puppeteer와의 통합, ProxyHat SDK 활용, 동시 요청 관리 방법을 코드 예제와 함께 설명합니다.

Node.js에서 프록시 사용하기 (Axios + Puppeteer + SDK)

Node.js에서 프록시가 필요한 이유

Node.js는 비동기 I/O로 인해 웹 스크래핑과 자동화에 뛰어난 선택입니다. 수백 개의 동시 요청을 효율적으로 처리할 수 있습니다. 하지만 프록시 없이는 대상 사이트가 빠르게 IP를 차단합니다.

이 가이드에서는 Node.js에서 프록시를 사용하는 모든 방법을 다룹니다 — Axios를 사용한 HTTP 요청, Puppeteer를 사용한 브라우저 자동화, ProxyHat SDK를 활용한 간편한 프록시 관리.

Axios로 프록시 사용하기

Axios는 Node.js에서 가장 인기 있는 HTTP 클라이언트입니다. 프록시 설정 방법:

import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';

const agent = new HttpsProxyAgent('http://user:pass@gate.proxyhat.com:8080');

const response = await axios.get('https://example.com/products', {
  httpsAgent: agent,
  timeout: 30000,
});

console.log(response.status);
console.log(response.data);

SOCKS5 프록시 사용

import axios from 'axios';
import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent('socks5://user:pass@gate.proxyhat.com:1080');

const response = await axios.get('https://example.com', {
  httpsAgent: agent,
  httpAgent: agent,
});
console.log(response.status);

ProxyHat Node SDK

ProxyHat Node SDK로 프록시 관리를 간소화합니다:

import { ProxyHat } from 'proxyhat';

const client = new ProxyHat({ apiKey: 'your_api_key' });

// 로테이팅 프록시로 GET 요청
const response = await client.get('https://example.com/products', {
  proxyType: 'residential',
  country: 'US',
});

console.log(response.status);
console.log(response.data);

// 자동 로테이션으로 동시 스크래핑
const urls = [
  'https://example.com/product/1',
  'https://example.com/product/2',
  'https://example.com/product/3',
];

const results = await Promise.all(
  urls.map(url => client.get(url, { proxyType: 'residential' }))
);
results.forEach(r => console.log(r.status));

Puppeteer와 프록시

Puppeteer로 헤드리스 브라우저에서 프록시를 사용하는 방법:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({
  args: ['--proxy-server=http://gate.proxyhat.com:8080'],
});

const page = await browser.newPage();

// 프록시 인증
await page.authenticate({
  username: 'your_username',
  password: 'your_password',
});

await page.goto('https://example.com/products');
const content = await page.content();
console.log(content.substring(0, 500));

await browser.close();

동시성 제어

대량 스크래핑 시 동시 요청 수를 제한하여 프록시 풀 과부하를 방지합니다:

import pLimit from 'p-limit';
import { ProxyHat } from 'proxyhat';

const client = new ProxyHat({ apiKey: 'your_api_key' });
const limit = pLimit(10); // 최대 10개 동시 요청

const urls = Array.from({ length: 100 }, (_, i) =>
  `https://example.com/product/${i + 1}`
);

const results = await Promise.all(
  urls.map(url =>
    limit(() => client.get(url, { proxyType: 'residential' }))
  )
);

console.log(`성공: ${results.filter(r => r.status === 200).length}`);

오류 처리

프록시 연결 오류를 적절히 처리합니다:

async function scrapeWithRetry(client, url, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await client.get(url, {
        proxyType: 'residential',
        timeout: 30000,
      });
      if (response.status === 200) return response;
    } catch (error) {
      console.log(`시도 ${attempt + 1} 실패: ${error.message}`);
      await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
    }
  }
  return null;
}

모범 사례

  • 동시성 제한 — p-limit 또는 유사 라이브러리로 동시 요청 수를 제한하십시오.
  • 타임아웃 설정 — 모든 요청에 적절한 타임아웃을 설정하십시오.
  • 재시도 로직 — 지수 백오프로 실패한 요청을 재시도하십시오.
  • 메모리 관리 — Puppeteer 사용 시 페이지와 브라우저를 적절히 닫아 메모리 누수를 방지하십시오.
  • 연결 풀링 — HTTP Agent를 재사용하여 연결 오버헤드를 줄이십시오.

핵심 요약

  • Node.js에서 Axios와 https-proxy-agent로 HTTP/SOCKS5 프록시를 쉽게 설정할 수 있습니다.
  • Puppeteer는 --proxy-server 인수와 page.authenticate()로 프록시를 지원합니다.
  • ProxyHat Node SDK는 자동 로테이션과 세션 관리를 제공합니다.
  • p-limit으로 동시성을 제어하여 프록시 풀 과부하를 방지하십시오.
  • ProxyHat 게이트웨이: gate.proxyhat.com, HTTP: 8080, SOCKS5: 1080.

Node.js 스크래핑을 시작하시겠습니까? ProxyHat 요금제를 확인하고 API 문서로 시작하십시오.

시작할 준비가 되셨나요?

AI 필터링으로 148개국 이상에서 5천만 개 이상의 레지덴셜 IP에 액세스하세요.

가격 보기레지덴셜 프록시
← 블로그로 돌아가기