mcpField
S
scraperapi-cli

scraperapi-cli

github.com/scraperapiデータ・データベース10107 回インストール12 週間前に更新
リポジトリ

scraperapi-cli について

scraperapi-cliは、アプリケーションコードを書かずに一度限りのスクレイピングやシェル処理を行うためのScraperAPIコマンドラインツールです。同期・非同期ジョブ、構造化データ、クロール、料金見積もりに対応します。

主な機能

  1. 01レンダリングとプロキシを設定したページ取得
  2. 02HTML、Markdown、テキスト、JSON、CSVの出力選択
  3. 03非同期スクレイピングジョブの送信と管理
  4. 04対応サイトの構造化データ取得
  5. 05クレジット料金の見積もりとアカウント設定管理

活用シーン

  1. 01取得結果をjqなどのシェルツールに渡す
  2. 02大量のURLをバッチジョブとして送信する
  3. 03cronで一度限りの定期スクレイピングを実行する
  4. 04実装前にレンダリングやプロキシの設定を試す

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/scraperapi/scraperapi-skills --skill scraperapi-cli

インストール後、Claude Code で/scraperapi-cliを入力して読み込まれたか確認します。

詳細

ScraperAPI CLI(sapi)

sapi は ScraperAPI の公式コマンドラインツールです。次のような場合に適しています。

  • ユーザーがすでにターミナルを使っていて、スクリプトを書かずに 今すぐ 結果を得たい場合。
  • スクレイピングがシェルパイプライン(sapi … | jq …、xargs、make、GitHub Actions)の一部である場合。
  • 単発のスケジュールタスク(cron、launchd、systemd timer)で、プロジェクトをセットアップせずに ScraperAPI にアクセスする必要がある場合。
  • ユーザーが機能を試している場合 — コードに設定を反映する前に、--render または --premium で対象サイトにアクセスできるかテストする場合。

ユーザーが Python、Node、PHP、Ruby、または Java でアプリケーションコードを書いている場合は、対応する SDK スキルを案内してください。CLI はシェル向けであり、アプリケーションロジック向けではありません。

インストールと認証

npm install -g scraperapi-cli    # requires Node.js 18+
sapi init                        # interactive: prompts for the key and validates it

非対話型セットアップ(CI/Dockerfile 向け):

sapi init --api-key "$SCRAPERAPI_API_KEY"
API キーの解決順序

sapi は次の順序で API キーを探し、最初に見つかったものを使用します。

  1. コマンドの --api-key <key> フラグ
  2. SCRAPERAPI_API_KEY 環境変数
  3. ~/.config/scraperapi/config.json(sapi init によって書き込まれます)

CI では環境変数を推奨します。シェルの履歴や設定ファイルにキーを残さずに済みます。

出力仕様 — パイプ処理で重要

ストリーム出力される内容
stdoutデータ(ページ本文、JSON、テーブル行)
stderrスピナー、警告、エラー

stdout が TTY ではない場合(パイプまたはリダイレクト)、sapi は自動的に JSON モードに切り替わります。

sapi scrape https://example.com | jq .body            # auto-JSON
sapi scrape https://example.com > out.json            # auto-JSON
sapi scrape https://example.com                       # human output (page body to stdout)

TTY で JSON モードを強制するには --json を指定します。本文形式を指定するには --output html|markdown|text|json|csv を使います。--output は TTY 以外での自動 JSON ルールを上書きするため、別のツールに渡す HTML や Markdown を JSON でラップせずにパイプ処理できます。

sapi は高額なリクエストでも確認を求めません。実行前にリクエストのコストを確認するには、sapi cost を使います。

sapi scrape <url> — 同期フェッチ

主力コマンドです。ページ本文を stdout に返します。

sapi scrape https://example.com
sapi scrape https://example.com --render                       # +10 credits, JS rendering
sapi scrape https://example.com --render --wait-for "#main"    # wait for selector
sapi scrape https://example.com --country gb                   # geotarget UK
sapi scrape https://example.com --premium                      # +10 credits, residential proxies
sapi scrape https://example.com --ultra-premium                # +30 credits, hardest sites
sapi scrape https://example.com --autoparse --json             # structured JSON for supported sites
sapi scrape https://example.com --screenshot --json            # PNG (+10 credits) returned as base64 in JSON
sapi scrape https://example.com --async                        # submit as async job, prints jobId
エスカレーション手順

常に最も低コストのオプションから始め、リクエストが失敗した場合にのみ段階的に上げます。

  1. デフォルト(1 クレジット)。200 なら完了です。
  2. ページが JavaScript でコンテンツを読み込む場合(SPA、ハイドレーションされたテーブル、無限スクロール)は --render を指定します。+10 クレジット。
  3. データセンター IP からのアクセスでサイトが 403 またはブロックページを返す場合は --premium を指定します。+10 クレジット。
  4. 最も強力なボット対策が施されたサイト(Cloudflare Turnstile、高度なフィンガープリンティング)の場合のみ --ultra-premium を指定します。+30 クレジット。

フラグを組み合わせるとクレジットが加算されます。--render --premium の場合、成功 1 回あたり約 20 クレジットです。

フラグのリファレンス
フラグ説明クレジット
--renderJavaScript のレンダリング+10
--premium住宅用プロキシ+10
--ultra-premium高度なボット対策の回避+30
--screenshotPNG スクリーンショット(JSON モードでは base64)+10
--autoparse対応サイト向けの自動解析済み JSON—
--country <cc>ISO 3166-1(例:us、gb、de)—
--device <type>mobile または desktop のユーザーエージェント—
--output <fmt>html、markdown、text、json、csv—
--session <n>固定セッション番号(IP を再利用)—
--wait-for <sel>待機する CSS セレクター(--render が必要)—
--timeout <sec>リクエストのタイムアウト(デフォルト 70)—
--async非同期ジョブとして送信し、ジョブ ID を表示して終了—
--jsonJSON 出力モードを強制—
--api-key <key>1 回の呼び出しに限り、設定済みの API キーを上書き—

対話型の確認手順はありません。sapi scrape はリクエストをすぐに実行します。クレジットを消費せずに使用量を確認するには、sapi cost <url>(以下を参照)を使います。

sapi cost <url> — クレジットコストのプレビュー

sapi cost https://example.com                   # base cost
sapi cost https://example.com --render          # with JS rendering
sapi cost https://example.com --render --premium
sapi cost https://example.com --render --json   # machine-readable

sapi scrape と同じパラメータフラグ(--async と --timeout を除く)を受け付け、25 credits のような値を表示します。高額な一括処理を実行する前の事前確認に便利です。選択したフラグの組み合わせが想定より高額な場合にすぐに失敗させたいときは、スクリプトに組み込んでください。

sapi jobs — 非同期スクレイピング

バッチ処理、応答の遅いターゲット、または完了を待たずに実行する処理には、非同期を使用します。

sapi scrape https://example.com --async              # returns a jobId on stdout
sapi jobs list                                        # list all jobs
sapi jobs get <jobId>                                 # poll until done, print result
sapi jobs get <jobId> --no-poll                       # one-shot status check
sapi jobs cancel <jobId>                              # cancel a running job
sapi jobs batch urls.txt                              # submit up to 50,000 URLs from a file

urls.txt には1行につき1つのURLを記載します。URLが約100件を超える場合は、バッチ処理が最適です。ループ内で同期的に sapi scrape を呼び出すと、同時リクエストの上限を消費し、429エラーが発生します。

慣用的なバッチパイプライン

sapi jobs batch はJSON配列を返します。送信されたジョブごとに1つのエントリがあり、それぞれに独自の id が付与されます。各子ジョブの状態は sapi jobs get で確認します。

# 1. Submit a batch, grab every child job id.
sapi jobs batch urls.txt --json | jq -r '.[].id' > job-ids.txt

# 2. Wait for each one (`jobs get` polls automatically until finished).
while read -r ID; do
  sapi jobs get "$ID" --json >> batch-results.ndjson
done < job-ids.txt

# 3. Extract bodies that succeeded.
jq -s '[.[] | select(.status=="finished") | .response.body]' batch-results.ndjson

sapi structured — 対応サイト向けの解析済みJSON

対象がAmazon、Google、Walmart、eBay、Redfinの場合は、scrape と --autoparse、手動解析を組み合わせるよりも、structured を優先してください。各エンドポイントは、整形済みでスキーマが安定したJSONを返します。

# Amazon
sapi structured amazon product https://amazon.com/dp/B09XYZ
sapi structured amazon search "wireless headphones"
sapi structured amazon offers https://amazon.com/dp/B09XYZ
sapi structured amazon reviews https://amazon.com/dp/B09XYZ

# Google
sapi structured google serp "best espresso machine"
sapi structured google news "artificial intelligence"
sapi structured google jobs "software engineer remote"
sapi structured google shopping "standing desk"
sapi structured google maps "coffee shops near me"

# Walmart / eBay / Redfin
sapi structured walmart product https://walmart.com/ip/123456
sapi structured ebay product https://ebay.com/itm/123456
sapi structured redfin listing https://redfin.com/home/12345
sapi structured redfin search "Austin TX"
sapi structured redfin agents "Portland OR"

すべての構造化コマンドは、未加工の出力を得るための --json を受け付けます(パイプに出力する場合は自動的に有効になります)。各分野のスキーマについては、docs.scraperapi.com を参照してください。

sapi crawler — サイト全体のクロール

sapi crawler start example.com           # kick off a crawl, prints jobId
sapi crawler status <jobId>              # progress
sapi crawler results <jobId>             # list discovered URLs (human table)
sapi crawler results <jobId> --json      # JSON object: { jobId, urls: [...] }

クローラーは、ドメイン全体からURLを見つけるためのものです。見つかった各URLをスクレイピングするには、結果を sapi jobs batch に渡します。

sapi crawler results "$CRAWL" --json | jq -r '.urls[]' > urls.txt
sapi jobs batch urls.txt

sapi pipeline — DataPipeline プロジェクト

プロジェクトは ScraperAPI dashboard で設定します。CLI では実行を開始し、結果を読み取れます。

sapi pipeline list                  # list your projects
sapi pipeline run <projectId>       # trigger a run, prints jobId
sapi pipeline status <jobId>        # check run status
sapi pipeline results <jobId>       # fetch results

ユーザーが定期的なスクレイピングを希望していて、まだプロジェクトがない場合は、ダッシュボードを案内してください。sapi ではプロジェクトを作成できません。

sapi account — クレジットとキーの管理

sapi account                        # human summary: credits left, plan, period
sapi account --json                 # machine-readable
sapi account keys list              # list API keys on the account
sapi account keys create            # create a new key (returns once — copy it)
sapi account keys revoke <keyId>    # revoke a key

大規模な処理を開始する前に、必ず sapi account を実行してください。キーが有効で、十分なクレジットがあることを確認する最も低コストな方法です。

sapi config — 永続的なデフォルト設定

sapi config list
sapi config get api_key
sapi config set default_country gb
sapi config set default_output_format markdown
sapi config set default_timeout 90

設定可能なキーは api_key、default_country、default_output_format、default_timeout です。マシンを共有している場合は、config set api_key の代わりに SCRAPERAPI_API_KEY 環境変数を使用してください。

シェルのレシピ

pup でスクレイピングしてタイトルを抽出し、CSV に追記する
URL="https://example.com"
TITLE=$(sapi scrape "$URL" --json | jq -r .body | pup 'title text{}')
echo "$URL,$TITLE" >> titles.csv
cron による毎日の価格チェック
# crontab: 7am every day
0 7 * * * /usr/local/bin/sapi structured amazon product https://amazon.com/dp/B09XYZ --json \
  | jq '{ts: now, price: .pricing}' >> ~/prices.ndjson
xargs による並列スクレイピング
# Run 5 in parallel; --json puts one record per line (no prompts to worry about).
cat urls.txt | xargs -n1 -P5 sapi scrape --render --json > out.ndjson

URLが約100件を超える場合は、同時リクエストの上限を回避できるため、こちらより sapi jobs batch を優先してください。

CI でエラーを確実に検出する

sapi はエラーが発生するとゼロ以外の終了コードを返すため、set -e は想定どおりに機能します。

set -euo pipefail
sapi account --json | jq -e '.credits > 1000'             # fails the build if low
sapi scrape "$URL" --output markdown > page.md
ブロックされた場合に段階的に切り替える
sapi scrape "$URL" --output html > out.html \
  || sapi scrape "$URL" --render --output html > out.html \
  || sapi scrape "$URL" --premium --output html > out.html

安価な方法から高価な方法へと進み、前の段階が失敗した場合にのみ次の段階の料金が発生します。--output html を指定すると、リダイレクトごとに未加工のHTMLが保持されます。これを指定しない場合、非TTYのルールにより本文はJSONでラップされます。

sapi を使わないほうがよい場合

  • アプリケーションコード内(Python、Node、PHP、Ruby、Java) — 対応するSDKのスキルを使用してください。CLIをシェルから呼び出す方法は壊れやすいためです。
  • シェルスクリプトで数千件のURLを短いループで処理する場合 — 代わりに sapi jobs batch でバッチを送信し、ScraperAPI に並行処理と再試行を任せてください。
  • Webhook 配信を伴う長時間実行のスケジュール済みプロジェクト — DataPipeline(ダッシュボードで設定)が適切な製品です。CLI では実行を開始できますが、プロジェクトモデルの代わりにはなりません。

トラブルシューティング

症状考えられる原因対処法
command not found: sapi未インストール、または npm のグローバル bin が $PATH にないnpm install -g scraperapi-cli を実行し、npm config get prefix を確認します
401 Invalid API keyキーがない、または間違っているsapi account を実行して確認し、sapi init を再実行します
公開ページで 403 が発生するデータセンターのIPがブロックされている--premium で再試行し、その後 --ultra-premium で再試行します
sapi から 429 が返される同時リクエストの上限に達したsapi jobs batch に切り替えるか、xargs -P の上限を追加します
スクリプトがいつまでも停止するデフォルトのタイムアウトは70秒で、ターゲットの応答が遅い--timeout 120 を指定するか、--async を使用します
出力がHTMLではなくJSONになるstdout がパイプに出力されているため、自動的にJSONになるパイプで未加工のHTMLが必要な場合は、--output html を指定します

全パラメーターのリファレンスと現在のクレジット料金については、docs.scraperapi.com を参照してください。

コメント