備忘録

備忘録

puppeteerでproxyを利用する方法

Ⅰ. はじめに

タイトルの通り「puppeteerでproxyを利用する方法」です。

Ⅱ. 方法1(起動引数を設定する)

  • この方法は認証無しのHTTP Proxyのみ設定出来ます

手順

1. サンプルプログラムを書く
const browser = await puppeteer.launch({
  args: [
    '--proxy-server=127.0.0.1:8080'
  ]
});

実行結果

省略

Ⅲ. 方法2(ライブラリを利用する方法)

手順

1. 必要なライブラリをインストールする
npm i puppeteer
npm i puppeteer-proxy

# HTTP, HTTPS
npm install https-proxy-agent

# SOCKS5
npm i socks-proxy-agent
2. サンプルプログラムを書く

index.js

const puppeteer = require('puppeteer');
const { proxyRequest } = require('puppeteer-proxy');
const HttpsProxyAgent = require('https-proxy-agent');
const SocksProxyAgent = require('socks-proxy-agent');

(async () => {
  const browser = await puppeteer.launch({ defaultViewport: null, headless: false, slowMo: 300 })
  const page = await browser.newPage()

  const agent = {
    http: new HttpsProxyAgent('http://127.0.0.1:3128'),
    https: new HttpsProxyAgent('http://127.0.0.1:3128'),
    // http: new HttpsProxyAgent('http://user:pass@127.0.0.1:3128'),
    // https: new HttpsProxyAgent('http://user:pass@127.0.0.1:3128'),
  }

  /*
  const agent = {
    http: new SocksProxyAgent('socks5://127.0.0.1:1080'),
    https: new SocksProxyAgent('socks5://127.0.0.1:1080'),
    // http: new SocksProxyAgent('socks5://user:pass@127.0.0.1:1080'),
    // https: new SocksProxyAgent('socks5://user:pass@127.0.0.1:1080'),
  }
  */

  await page.setRequestInterception(true);
  page.on('request', async (request) => {
    await proxyRequest({
      agent,
      page,
      request,
    });
  });

  await page.goto('https://api.ipify.org/')
})()

実行結果

省略