Scraping Browserガイドコストの最適化

コスト最適化

はじめに

Puppeteerを用いたデータスクレイピングにおいて、トラフィック消費は重要な考慮事項です。特にプロキシサービスを利用する場合、トラフィックコストは大幅に増加する可能性があります。トラフィック使用量を最適化するために、以下の戦略を採用できます。

  1. リソースインターセプト: 不要なリソースリクエストをインターセプトすることで、トラフィック消費を削減します。
  2. リクエストURLインターセプト: URLの特徴に基づいて特定のリクエストをインターセプトすることで、さらにトラフィックを削減します。
  3. モバイルデバイスのシミュレーション: モバイルデバイスの設定を使用することで、より軽量なページバージョンを取得します。
  4. 包括的な最適化: 上記の方法を組み合わせて、最適な結果を実現します。

最適化スキーム1: リソースインターセプト

リソースインターセプトの概要

Puppeteerでは、page.setRequestInterception(true)を使用することで、ブラウザによって開始されたすべてのネットワークリクエストをキャプチャし、継続(request.continue()), 終了(request.abort()), またはレスポンスのカスタマイズ(request.respond())を決定できます。

この方法は、帯域幅消費を大幅に削減でき、特にクロールスクリーンショットパフォーマンス最適化のシナリオに適しています。

インターセプト可能なリソースの種類と推奨事項

リソースの種類説明インターセプト後の影響推奨度
image画像リソースJPG/PNG/GIF/WebP画像画像が表示されなくなります⭐ 安全
fontフォントファイルTTF/WOFF/WOFF2フォントシステムデフォルトフォントが代わりに使用されます⭐ 安全
mediaメディアファイル映像/音声ファイルメディアコンテンツを再生できません⭐ 安全
manifestWebアプリマニフェストPWA設定ファイルPWA機能が影響を受ける可能性があります⭐ 安全
prefetchプリフェッチリソース<link rel="prefetch">ページへの影響は最小限です⭐ 安全
stylesheetCSSスタイルシート外部CSSファイルページスタイルが失われ、レイアウトに影響する可能性があります⚠️ 注意
websocketWebSocketリアルタイム通信接続リアルタイム機能が無効になります⚠️ 注意
eventsourceサーバーセントイベントサーバプッシュデータプッシュ機能が無効になります⚠️ 注意
preflightCORSプリフライトリクエストOPTIONSリクエストクロスオリジンリクエストが失敗します⚠️ 注意
scriptJavaScriptスクリプト外部JSファイル動的な機能が無効になり、SPAがレンダリングされない可能性があります❌ 避ける
xhrXHRリクエストAJAXデータリクエスト動的なデータを取得できません❌ 避ける
fetchFetchリクエスト最新のAJAXリクエスト動的なデータを取得できません❌ 避ける
documentメインドキュメントHTMLページ自体ページを読み込めません❌ 避ける

推奨レベルの説明:

  • 安全: インターセプトはデータスクレイピングやファーストビューのレンダリングにほとんど影響を与えません。デフォルトでブロックすることを推奨します。
  • ⚠️ 注意: スタイル、リアルタイム機能、またはクロスオリジンリクエストを壊す可能性があります。ビジネス上の判断が必要です。
  • 避ける: SPA/動的なサイトが正常にレンダリングまたはデータを取得できなくなる可能性が高いため、これらのリソースが絶対に必要ない場合を除いて避けてください。

リソースインターセプトのコード例

import puppeteer from 'puppeteer-core';
 
const scrapelessUrl = 'wss://browser.scrapeless.com/browser?token=your_api_key&session_ttl=180&proxy_country=ANY';
 
async function scrapeWithResourceBlocking(url) {
    const browser = await puppeteer.connect({
        browserWSEndpoint: scrapelessUrl,
        defaultViewport: null
    });
    const page = await browser.newPage();
 
    // リクエストインターセプトを有効化
    await page.setRequestInterception(true);
 
    // ブロックするリソースタイプを定義
    const BLOCKED_TYPES = new Set([
        'image',
        'font',
        'media',
        'stylesheet',
    ]);
 
    // リクエストをインターセプト
    page.on('request', (request) => {
        if (BLOCKED_TYPES.has(request.resourceType())) {
            request.abort();
            console.log(`Blocked: ${request.resourceType()} - ${request.url().substring(0, 50)}...`);
        } else {
            request.continue();
        }
    });
 
    await page.goto(url, {waitUntil: 'domcontentloaded'});
 
    // データを抽出
    const data = await page.evaluate(() => {
        return {
            title: document.title,
            content: document.body.innerText.substring(0, 1000)
        };
    });
 
    await browser.close();
    return data;
}
 
// 使用例
scrapeWithResourceBlocking('https://www.scrapeless.com')
    .then(data => console.log('Scraping result:', data))
    .catch(error => console.error('Scraping failed:', error));

最適化スキーム2: リクエストURLインターセプト

リソースタイプによるインターセプトに加えて、URLの特徴に基づいてより詳細なインターセプト制御を実行できます。これは、広告、分析スクリプト、その他の不要なサードパーティリクエストをブロックする場合に特に効果的です。

URLインターセプト戦略

  1. ドメインによるインターセプト: 特定のドメインからのすべてのリクエストをブロックします。
  2. パスによるインターセプト: 特定のパスからのリクエストをブロックします。
  3. ファイルタイプによるインターセプト: 特定の拡張子を持つファイルをブロックします。
  4. キーワードによるインターセプト: URLに特定のキーワードが含まれているリクエストをブロックします。

一般的なインターセプト可能なURLパターン

URLパターン説明推奨度
広告サービス広告ネットワークドメインad.doubleclick.net, googleadservices.com⭐ 安全
分析サービス統計と分析スクリプトgoogle-analytics.com, hotjar.com⭐ 安全
ソーシャルメディアプラグインソーシャル共有ボタンなどplatform.twitter.com, connect.facebook.net⭐ 安全
トラッキングピクセルユーザー行動を追跡するピクセルpixelbeacontrackerを含むURL⭐ 安全
大容量メディアファイル大容量の動画、音声ファイル.mp4.webm.mp3などの拡張子⭐ 安全
フォントサービスオンラインフォントサービスfonts.googleapis.com, use.typekit.net⭐ 安全
CDNリソース静的リソースCDNcdn.jsdelivr.net, unpkg.com⚠️ 注意

URLインターセプトのコード例

import puppeteer from 'puppeteer-core';
 
const scrapelessUrl = 'wss://browser.scrapeless.com/browser?token=your_api_key&session_ttl=180&proxy_country=ANY';
 
async function scrapeWithUrlBlocking(url) {
    const browser = await puppeteer.connect({
        browserWSEndpoint: scrapelessUrl,
        defaultViewport: null
    });
    const page = await browser.newPage();
 
    // リクエストインターセプトを有効化
    await page.setRequestInterception(true);
 
    // ブロックするドメインとURLパターンを定義
    const BLOCKED_DOMAINS = [
        'google-analytics.com',
        'googletagmanager.com',
        'doubleclick.net',
        'facebook.net',
        'twitter.com',
        'linkedin.com',
        'adservice.google.com',
    ];
 
    const BLOCKED_PATHS = [
        '/ads/',
        '/analytics/',
        '/pixel/',
        '/tracking/',
        '/stats/',
    ];
 
    // リクエストをインターセプト
    page.on('request', (request) => {
        const url = request.url();
 
        // ドメインをチェック
        if (BLOCKED_DOMAINS.some(domain => url.includes(domain))) {
            request.abort();
            console.log(`Blocked domain: ${url.substring(0, 50)}...`);
            return;
        }
 
        // パスをチェック
        if (BLOCKED_PATHS.some(path => url.includes(path))) {
            request.abort();
            console.log(`Blocked path: ${url.substring(0, 50)}...`);
            return;
        }
 
        // その他のリクエストを許可
        request.continue();
    });
 
    await page.goto(url, {waitUntil: 'domcontentloaded'});
 
    // データを抽出
    const data = await page.evaluate(() => {
        return {
            title: document.title,
            content: document.body.innerText.substring(0, 1000)
        };
    });
 
    await browser.close();
    return data;
}
 
// 使用例
scrapeWithUrlBlocking('https://www.scrapeless.com')
    .then(data => console.log('Scraping result:', data))
    .catch(error => console.error('Scraping failed:', error));

最適化スキーム3: モバイルデバイスのシミュレーション

モバイルデバイスをシミュレートすることは、モバイルサイトは通常より軽量なページコンテンツを提供するため、もう1つの効果的なトラフィック最適化戦略です。

モバイルデバイスシミュレーションの利点

  1. 軽量なページバージョン: 多くのウェブサイトはモバイルデバイスに対してより簡潔なコンテンツを提供します。
  2. 小さな画像リソース: モバイルバージョンは通常、小さな画像を読み込みます。
  3. 簡素化されたCSSとJavaScript: モバイルバージョンは通常、簡素化されたスタイルとスクリプトを使用します。
  4. 広告と非コアコンテンツの削減: モバイルバージョンは多くの場合、一部の非コア機能を削除します。
  5. 適応型レスポンス: 小さな画面に最適化されたコンテンツレイアウトを取得します。

モバイルデバイスシミュレーション設定

いくつかの一般的に使用されるモバイルデバイスの設定パラメーターを以下に示します。

const iPhoneX = {
    viewport: {
        width: 375,
        height: 812,
        deviceScaleFactor: 3,
        isMobile: true,
        hasTouch: true,
        isLandscape: false
    }
};

または、puppeteerの組み込みメソッドを使用してモバイルデバイスを直接シミュレートします。

import { KnownDevices } from 'puppeteer-core';
const iPhone = KnownDevices['iPhone 15 Pro'];
 
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(iPhone);

モバイルデバイスシミュレーションのコード例

import puppeteer, {KnownDevices} from 'puppeteer-core';
 
const scrapelessUrl = 'wss://browser.scrapeless.com/browser?token=your_api_key&session_ttl=180&proxy_country=ANY';
 
async function scrapeWithMobileEmulation(url) {
    const browser = await puppeteer.connect({
        browserWSEndpoint: scrapelessUrl,
        defaultViewport: null
    });
 
    const page = await browser.newPage();
 
    // モバイルデバイスシミュレーションを設定
    const iPhone = KnownDevices['iPhone 15 Pro'];
    await page.emulate(iPhone);
 
    await page.goto(url, {waitUntil: 'domcontentloaded'});
    // データを抽出
    const data = await page.evaluate(() => {
        return {
            title: document.title,
            content: document.body.innerText.substring(0, 1000)
        };
    });
 
    await browser.close();
    return data;
}
 
// 使用例
scrapeWithMobileEmulation('https://www.scrapeless.com')
    .then(data => console.log('Scraping result:', data))
    .catch(error => console.error('Scraping failed:', error));

包括的な最適化例

すべての最適化スキームを組み合わせた包括的な例を以下に示します。

import puppeteer, {KnownDevices} from 'puppeteer-core';
 
const scrapelessUrl = 'wss://browser.scrapeless.com/browser?token=your_api_key&session_ttl=180&proxy_country=ANY';
 
async function optimizedScraping(url) {
    console.log(`Starting optimized scraping: ${url}`);
 
    // トラフィック使用量を記録
    let totalBytesUsed = 0;
 
    const browser = await puppeteer.connect({
        browserWSEndpoint: scrapelessUrl,
        defaultViewport: null
    });
 
    const page = await browser.newPage();
 
    // モバイルデバイスシミュレーションを設定
    const iPhone = KnownDevices['iPhone 15 Pro'];
    await page.emulate(iPhone);
 
    // リクエストインターセプトを設定
    await page.setRequestInterception(true);
 
    // ブロックするリソースタイプを定義
    const BLOCKED_TYPES = [
        'image',
        'media',
        'font'
    ];
 
    // ブロックするドメインを定義
    const BLOCKED_DOMAINS = [
        'google-analytics.com',
        'googletagmanager.com',
        'facebook.net',
        'doubleclick.net',
        'adservice.google.com'
    ];
 
    // ブロックするURLパスを定義
    const BLOCKED_PATHS = [
        '/ads/',
        '/analytics/',
        '/tracking/'
    ];
 
    // リクエストをインターセプト
    page.on('request', (request) => {
        const url = request.url();
        const resourceType = request.resourceType();
 
        // リソースタイプをチェック
        if (BLOCKED_TYPES.includes(resourceType)) {
            console.log(`Blocked resource type: ${resourceType} - ${url.substring(0, 50)}...`);
            request.abort();
            return;
        }
 
        // ドメインをチェック
        if (BLOCKED_DOMAINS.some(domain => url.includes(domain))) {
            console.log(`Blocked domain: ${url.substring(0, 50)}...`);
            request.abort();
            return;
        }
 
        // パスをチェック
        if (BLOCKED_PATHS.some(path => url.includes(path))) {
            console.log(`Blocked path: ${url.substring(0, 50)}...`);
            request.abort();
            return;
        }
 
        // その他のリクエストを許可
        request.continue();
    });
 
    // ネットワークトラフィックを監視
    page.on('response', async (response) => {
        const headers = response.headers();
        const contentLength = headers['content-length'] ? parseInt(headers['content-length'], 10) : 0;
        totalBytesUsed += contentLength;
    });
 
    await page.goto(url, {waitUntil: 'domcontentloaded'});
 
    // 遅延読み込みコンテンツをトリガーするためにスクロールをシミュレート
    await page.evaluate(() => {
        window.scrollBy(0, window.innerHeight);
    });
 
    await new Promise(resolve => setTimeout(resolve, 1000))
 
    // データを抽出
    const data = await page.evaluate(() => {
        return {
            title: document.title,
            content: document.body.innerText.substring(0, 1000),
            links: Array.from(document.querySelectorAll('a')).slice(0, 10).map(a => ({
                text: a.innerText,
                href: a.href
            }))
        };
    });
 
    // トラフィック使用量統計を出力
    console.log(`\nTraffic Usage Statistics:`);
    console.log(`Used: ${(totalBytesUsed / 1024 / 1024).toFixed(2)} MB`);
 
    await browser.close();
    return data;
}
 
// 使用例
optimizedScraping('https://www.scrapeless.com')
    .then(data => console.log('Scraping complete:', data))
    .catch(error => console.error('Scraping failed:', error));

最適化比較

最適化されたコードを包括的な例から削除して、最適化前後のトラフィックを比較してみます。最適化されていないコード例を以下に示します。

import puppeteer from 'puppeteer-core';
 
const scrapelessUrl = 'wss://browser.scrapeless.com/browser?token=your_api_key&session_ttl=180&proxy_country=ANY';
 
async function unoptimizedScraping(url) {
  console.log(`Starting unoptimized scraping: ${url}`);
 
  // Record traffic usage
  let totalBytesUsed = 0;
 
  const browser = await puppeteer.connect({
    browserWSEndpoint: scrapelessUrl,
    defaultViewport: null
  });
 
  const page = await browser.newPage();
 
  // Set request interception
  await page.setRequestInterception(true);
 
  // Intercept requests
  page.on('request', (request) => {
    request.continue();
  });
 
  // Monitor network traffic
  page.on('response', async (response) => {
    const headers = response.headers();
    const contentLength = headers['content-length'] ? parseInt(headers['content-length'], 10) : 0;
    totalBytesUsed += contentLength;
  });
 
  await page.goto(url, {waitUntil: 'domcontentloaded'});
 
  // Simulate scrolling to trigger lazy-loading content
  await page.evaluate(() => {
    window.scrollBy(0, window.innerHeight);
  });
 
  await new Promise(resolve => setTimeout(resolve, 1000))
 
  // Extract data
  const data = await page.evaluate(() => {
    return {
      title: document.title,
      content: document.body.innerText.substring(0, 1000),
      links: Array.from(document.querySelectorAll('a')).slice(0, 10).map(a => ({
        text: a.innerText,
        href: a.href
      }))
    };
  });
 
  // Output traffic usage statistics
  console.log(`\nTraffic Usage Statistics:`);
  console.log(`Used: ${(totalBytesUsed / 1024 / 1024).toFixed(2)} MB`);
 
  await browser.close();
  return data;
}
 
// Usage
unoptimizedScraping('https://www.scrapeless.com')
  .then(data => console.log('Scraping complete:', data))
  .catch(error => console.error('Scraping failed:', error));

最適化されていないコードを実行した後、出力された情報からトラフィックの差を非常に直感的に確認できます。

シナリオ使用トラフィック (MB)削減率
最適化前6.03
最適化後0.81≈ 86.6 %

上記最適化スキームを組み合わせることで、プロキシのトラフィック消費を大幅に削減し、スクレイピング効率を向上させ、必要なコアコンテンツを取得できます。