統合

Shifterと一緒に使用する Cheerio

ShifterのレジデンシャルおよびISPプロキシをCheerioと組み合わせることで、高速で軽量なNodeスクレイピングを実現できます。CheerioがjQueryスタイルのHTMLパースを担い、Shifterがレジデンシャル IPを提供するため、ヘッドレスブラウザは不要です。

クイックスタート

インストール

npm install cheerio axios https-proxy-agent

基本的な使い方

import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";

const proxyUrl =
  "customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443";

const { data: html } = await axios.get("https://example.com", {
  httpsAgent: new HttpsProxyAgent(proxyUrl),
  proxy: false,
});

const $ = load(html);
console.log($("h1").text());

$("article.post").each((_, el) => {
  console.log($(el).find("h2").text(), "->", $(el).find("a").attr("href"));
});

機能

axios、got、got-scraping、undici、およびプロキシURLをサポートする任意のHTTPクライアントとスムーズに連携します
デフォルトはリクエストごとのローテーション。スティッキーセッションには`sid`、N秒間のタイムドピンには`ttl-N`を使用
Crawlee、Apify、および プロキシ URL を受け付けるあらゆる本番クローラーフレームワークと互換性あり
ユーザー名パラメータを使用した 195+ か国での Geo ターゲティング -- 国、地域、都市、ASN
静的またはJSが少ないターゲットに対し、ヘッドレスブラウザスクレイピングより桁違いに高速
TypeScript、ESM、CommonJS、およびNode.js LTS 14以降のすべてのバージョンと互換性あり

スティッキーセッション + 複数ページクロール

複数ページにわたるクロールの間、レジデンシャル IP を 1 つ固定します。ジオターゲティングには `country-uk` を、スティッキーウィンドウを 5 分に延長するには `ttl-300` を追加してください。

import axios, { type AxiosInstance } from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";
import { randomBytes } from "node:crypto";

function makeClient(country: string): AxiosInstance {
  const sid = randomBytes(4).toString("hex");
  const proxyUrl =
    `customer-USERNAME-country-${country}-sid-${sid}-ttl-300:` +
    `PASSWORD@p.shifter.io:443`;

  return axios.create({
    httpsAgent: new HttpsProxyAgent(proxyUrl),
    proxy: false,
    timeout: 30_000,
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
      "Accept-Language": "en-US,en;q=0.9",
    },
  });
}

const client = makeClient("uk");

let url: string | null = "https://example.co.uk/products";
const products: { title: string; price: string }[] = [];

while (url) {
  const { data: html } = await client.get(url);
  const $ = load(html);

  $(".product-card").each((_, el) => {
    products.push({
      title: $(el).find("h2").text().trim(),
      price: $(el).find(".price").text().trim(),
    });
  });

  const next = $("a.next-page").attr("href");
  url = next ? new URL(next, url).toString() : null;
}

console.log(`Scraped ${products.length} products`);

並列スクレイピング(リクエストごとのローテーション)

リクエストごとのローテーションにはsidを削除してください。並列フェッチのたびに異なるレジデンシャル IPが割り当てられ、URLのリストをIPあたりのレート制限に引っかからずに処理するのに最適です。

import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";

function rotatingClient() {
  // No sid -> Shifter rotates the residential IP per request.
  const proxyUrl =
    "customer-USERNAME-country-us:PASSWORD@p.shifter.io:443";

  return axios.create({
    httpsAgent: new HttpsProxyAgent(proxyUrl),
    proxy: false,
    timeout: 30_000,
  });
}

async function scrape(url: string) {
  const client = rotatingClient();
  const { data: html } = await client.get(url);
  const $ = load(html);

  return {
    url,
    title: $("h1").first().text().trim(),
    headings: $("h2").map((_, el) => $(el).text().trim()).get(),
  };
}

const urls = [
  "https://example.com/category/laptops",
  "https://example.com/category/phones",
  "https://example.com/category/tablets",
  "https://example.com/category/wearables",
];

const results = await Promise.all(urls.map(scrape));
console.log(results);

got-scraping (ブラウザフィンガープリント内蔵)

got-scraping は got をベースにリアルなヘッダー生成機能を組み込んでいます。Shifter と組み合わせることで、Puppeteer より 100 倍高速なブラウザ形状の小型 HTTP スクレイパーを実現できます。

// npm install got-scraping cheerio
import { gotScraping } from "got-scraping";
import { load } from "cheerio";

const proxyUrl =
  "customer-USERNAME-country-de-city-berlin-sid-456DEF:PASSWORD@p.shifter.io:443";

const html = await gotScraping({
  url: "https://example.de/products",
  proxyUrl,
  headerGeneratorOptions: {
    browsers: [{ name: "chrome", minVersion: 120 }],
    devices: ["desktop"],
    locales: ["de-DE", "en"],
    operatingSystems: ["macos", "linux"],
  },
}).text();

const $ = load(html);

$(".product").each((_, el) => {
  console.log({
    title: $(el).find("h2").text().trim(),
    price: $(el).find(".price").text().trim(),
  });
});

Crawlee(Shifterを使った本番クローラー)

Crawlee(Apify製)はキュー、リトライ、永続化、プロキシローテーションをすぐに処理します。ShifterをProxyConfigurationとして組み込み、残りはCrawleeに任せましょう。

// npm install crawlee cheerio
import { CheerioCrawler, ProxyConfiguration } from "crawlee";

const proxyConfiguration = new ProxyConfiguration({
  newUrlFunction: () => {
    // New residential IP per session. Crawlee rotates sessions
    // automatically on bans, so stale IPs get cycled out.
    const sid = Math.random().toString(36).slice(2, 10);
    return `customer-USERNAME-country-fr-sid-${sid}:PASSWORD@p.shifter.io:443`;
  },
});

const crawler = new CheerioCrawler({
  proxyConfiguration,
  maxConcurrency: 8,
  async requestHandler({ request, $, enqueueLinks, log }) {
    log.info(`${request.url} -> ${$("h1").text().trim()}`);

    $(".article").each((_, el) => {
      log.info(`  ${$(el).find("h2").text().trim()}`);
    });

    await enqueueLinks({ selector: "a.next-page", strategy: "same-domain" });
  },
});

await crawler.run([
  "https://example.fr/blog",
  "https://example.fr/news",
]);
FAQ

よくある質問

Shifter と Cheerio の併用に関するよくある質問。

いいえ。CheerioはパーサーでありHTTPリクエストは行いません。プロキシはCheerioと組み合わせるHTTPクライアント(axios、got、undici、fetch)に設定します。ShifterでHTMLを取得したら、それをCheerioのload()関数に渡すだけです。

https-proxy-agentを使用してaxiosをp.shifter.io:443(認証情報をインラインで指定)に向けて設定します。ページを取得し、response.dataをcheerio.load()に渡して、jQueryと同様にクエリを実行します。全体のセットアップは約10行のコードです。

必要なデータが最初のHTMLペイロードに含まれている場合は常にCheerioを使用してください。ヘッドレスChromeより10〜100倍高速で、メモリ使用量もごくわずかです。ページがJavaScript経由でクライアントサイドのコンテンツをハイドレートする場合にのみ、PuppeteerまたはPlaywrightに切り替えてください。

プロキシのユーザー名にセッションIDを追加してください。例:`customer-USERNAME-country-us-sid-123ABC`。クロール実行中のすべてのフェッチで同じaxiosインスタンスを再利用すると、Shifterは同じレジデンシャルIPを返し続けます。`ttl-N`を追加すると有効期間を延長できます。

はい。Crawleeにはキューイング、リトライ、並行処理を処理するCheerioCrawlerが付属しています。CrawleeのProxyConfigurationにnewUrlFunctionを設定し、セッションごとに一意のsidを持つ新しいShifter URLを返すようにしてShifterを設定してください。

はい。got-scrapingは `proxyUrl` オプションを受け付け、プロキシのネゴシエーションを透過的に処理します。実際のブラウザフィンガープリントを模倣する組み込みのヘッダージェネレーターと組み合わせることで、ヘッドレスブラウザに代わる優れた軽量の選択肢となります。

始める

でShifterを使い始める Cheerio

Shifterの205M+件のレジデンシャルおよびISPプロキシをCheerioと組み合わせることで、高速で軽量なNodeスクレイピングを実現できます。リクエスト単位のローテーション、スティッキーセッション、Crawleeの完全サポートに対応しています。

Shifterを無料で試す数分でセットアップ完了。いつでもキャンセル可能。