なぜNode.jsでプロキシを使用するのですか?
Node.jsは、Webスクレーパー、APIインテグレータ、および自動化ツールを構築する最も一般的なランタイムの1つです。 しかし、単一のIPアドレスから数百または数千の要求を送信している場合は、すぐに速度制限、CAPTCHA、および直立IP禁止に実行されます。 Node.jsのプロキシ 異なるIPアドレスでリクエストをルーティングすることで、それぞれが一意のユーザーから来られるようにします。
製品の価格をスクレイピングしたり、検索エンジンのランキングを監視したり、パブリックデータをスケールで収集したりする場合でも、プロキシは不可欠です。 このガイドでは、住宅のプロキシをNode.jsプロジェクトに統合するために必要なすべてをカバーします。 ProxyHat ノード SDK、軸線、Puppeteer、Playwright。
プロキシタイプがあなたのユースケースに合っていることをまだ評価している場合は、当社の比較を確認してください 住宅対データセンター対モバイルプロキシ. .
インストールとセットアップ
ProxyHat SDKのインストール
スタートする最速の方法は、公式 Node SDK です。 認証、回転、接続のプールを箱から処理します。
npm install proxyhatまた、使用するHTTPクライアントも必要です。
npm install axios puppeteer playwright認証
すべての ProxyHat プロキシ接続は、API 認証情報から認証されます。 ユーザー名とパスワードは、 ProxyHatダッシュボード.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 クライアントです。 ProxyHat で Axios リクエストをルーティングするには、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形式を標準プロキシ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は、JavaScript-heavyウェブサイトをスクレイピングするのに理想的な、ヘッドレスのChromeブラウザを起動します。 ブラウザの起動レベルでプロキシを設定しています。
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();ジオターゲティングの人形
特定の国をターゲットにするには、ユーザー名に国のコードを記述します。 ProxyHat はフォーマットを使用する USERNAME-country-XX: : :
await page.authenticate({
username: 'USERNAME-country-de', // Route through Germany
password: 'PASSWORD',
});すべての利用可能なプロキシの場所を閲覧 サイトマップ. .
Playwrightでプロキシを使用する
PlaywrightはChromium、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'),
]);回転対粘着セッション
ProxyHatは、異なるスクレイピングニーズに対応する2つのセッションモードをサポートしています。
| スタッフ | 回転 | スティッキー |
|---|---|---|
| 要求ごとのIP | 毎回新しいIP | セッション期間の同じIP |
| 最高の | 大規模スクレイピング | 複数のワークフロー、ログインセッション |
| セッション期間 | N・A | 最長30分 |
| ユーザー名形式 | USERNAME | USERNAME-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トラッキング、ローカライズされた価格の監視および地域コンテンツの検証。 ProxyHat は、ユーザー名の文字列をターゲットとする国レベルと都市レベルをサポートしています。
// 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'
);完全なリストを確認する 利用可能な場所 各国・都市の支援
エラー処理と復元
スケールでプロキシを扱うときにネットワークエラーは避けられない。 堅牢な再試行戦略は、生産スクレーパーにとって不可欠です。
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 マシンとターゲットサーバーの両方を圧倒できます。 並列接続数を制御するためにconcurrencyリミッターを使用します。
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 });
});大規模に ウェブスクレイピングプロジェクト速度と信頼性の両立性が良好である5~20の両立を保ちます。 ガイドを読む 2026年にWebスクレイピングに最適なプロキシ より多くの建築の助言のため。
生産のヒント
接続管理
- Axiosインスタンスとプロキシエージェントを再利用し、リクエストごとに新しいものを生成します。 これはソケットの排気を避けます。
- セット
keepAlive: true永続接続のためのHTTPエージェントに。 - Puppeteer/Playwrightブラウザを無償メモリに使用後速やかに閉じます。
記憶およびタイムアウト
- Puppeteerのために、使用して下さい
page.setRequestInterception(true)HTML コンテンツのみを必要とするときに画像、CSS、フォントをブロックします。 帯域幅やメモリ使用量を大幅に削減します。 - リクエストごとに明示的なタイムアウトを常に設定します。 欠けているタイムアウトは、スクレーパーをぶら下げる原因の1つです。
- Node.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`;始める準備は? チェックイン プライシングプラン プロジェクトに適した住宅プロキシ帯域幅を見つける。
キーテイクアウト
- ザ・オブ・ザ・ ProxyHat ノード SDK プロキシサポートを追加する最速の方法です。 インストール
npm install proxyhat3行のコードでフェッチを始めます。- アキシオス プロキシを介した作品
https-proxy-agentSDK の組み込みエージェント 再使用可能な Axios インスタンスを効率性のために作成します。- パプピーター 起動引数としてプロキシを受け入れる。 電話番号
page.authenticate()認証情報を渡します。- プレイライト 多項式スクレイピングのためのパーコンテキストプロキシを含む、起動およびコンテキストオプションでネイティブプロキシのサポートを持っています。
- 使用条件 スティッキーセッション 複数のワークフローと 回転IP 大規模なデータ収集のため。
- 常に実装 指数関数的なバックオフによる再試行ロジック そして、 通貨制御 生産のスクレーパーで。
- 不要なリソースをヘッドレスブラウザでブロックし、帯域幅を減らし、速度を改善します。






