mcpField
S
scraperapi-ruby-sdk

scraperapi-ruby-sdk

github.com/scraperapi開発1099 回インストール12 週間前に更新
リポジトリ

scraperapi-ruby-sdk について

scraperapi-ruby-sdkは、Ruby開発者向けのScraperAPI Ruby SDK利用ガイドです。同期スクレイピング、リクエスト設定、エラー処理に加え、バッチ用の非同期エンドポイントやJSON向け構造化データエンドポイントを扱います。

主な機能

  1. 01RubyクライアントでのURL取得
  2. 02レンダリング、プロキシ、地域指定の設定
  3. 03セッションによるプロキシIPの再利用
  4. 04非同期バッチジョブの送信
  5. 05構造化データエンドポイントへのリクエスト

活用シーン

  1. 01WebページのHTML取得
  2. 02JavaScriptレンダリングページのスクレイピング
  3. 03同一ドメインでのページ送り処理
  4. 0420件以上のURLのバッチ処理

インストール

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

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

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

詳細

ScraperAPI — Ruby SDK のベストプラクティス

必要要件: Ruby >= 2.0、gem install scraperapi(または Gemfile に gem 'scraperapi')、SCRAPERAPI_API_KEY 環境変数。

セットアップ

require "scraper_api"

client = ScraperAPI::Client.new(ENV["SCRAPERAPI_API_KEY"])

API キーをハードコードしないでください。毎回、環境変数から読み込んでください。

基本的な使い方

# Simple GET — returns raw HTML string via .raw_body
html = client.get("https://example.com/").raw_body
puts html

# With a single parameter
html = client.get("https://example.com/", render: true).raw_body

# With multiple parameters
html = client.get(
  "https://example.com/",
  render: true,
  country_code: "us"
).raw_body

パラメーターは URL の後にキーワード引数として渡します。.raw_body はレスポンスオブジェクトから HTML 文字列を抽出します。

選択ガイド

状況方法
単一 URL、同期処理client.get(url, **params).raw_body
ページが JavaScript でコンテンツを読み込むrender: true を渡します
サイトがデータセンタープロキシをブロックするpremium: true を渡します
最も強力なボット対策ultra_premium: true を渡します
同じドメインでの複数ステップ/ページネーション処理session_number: を使用します
20 件以上の URL またはバッチジョブNet::HTTP または Faraday を使用して非同期エンドポイントを利用します
対応プラットフォーム(Amazon、Google など)構造化データエンドポイントを直接使用します

パラメーターリファレンス

レンダリング
# Render JavaScript before returning HTML
# Use when: page is a React/Vue/Angular SPA, or initial scrape returns empty/partial content
# Cost: +10 credits
html = client.get("https://spa-site.com/", render: true).raw_body

# Wait for a specific DOM element (requires render: true)
html = client.get(
  "https://spa-site.com/",
  render: true,
  wait_for_selector: ".product-list"
).raw_body

デフォルトで render: true を追加しないでください。まずは指定せずに試してください。コストとレイテンシが増加します。

プロキシと位置情報ターゲティング
# Route through a country-specific proxy — no extra credit cost
html = client.get("https://example.com/", country_code: "gb").raw_body

# Premium residential/mobile IPs — for sites that block datacenter proxies
# Cost: 10 credits (25 with render: true)
html = client.get("https://hard-site.com/", premium: true).raw_body

# Ultra-premium — for the toughest anti-bot protections
# Cost: 30 credits (75 with render: true)
# Note: incompatible with keep_headers — custom headers are discarded
html = client.get("https://hardest-site.com/", ultra_premium: true).raw_body

premium と ultra_premium は同時に使用できません。両方を渡さないでください。 段階的な切り替え順序:標準(1 cr)→ render(10 cr)→ premium(10 cr)→ ultra_premium(30 cr)。

セッション(固定プロキシ)
# Reuse the same proxy IP across requests — useful for pagination and multi-step flows
# Sessions expire 15 minutes after last use; any integer is a valid session ID
html1 = client.get("https://example.com/page1", session_number: 42).raw_body
html2 = client.get("https://example.com/page2", session_number: 42).raw_body
ヘッダーとデバイスタイプ
# Forward custom headers to the target site
# Note: keep_headers is ignored when ultra_premium: true
html = client.get(
  "https://example.com/",
  keep_headers: true
  # Pass additional headers via the underlying request object as needed
).raw_body

# Emulate a mobile or desktop browser user-agent
html = client.get("https://example.com/", device_type: "mobile").raw_body
自動パース
# Return structured JSON instead of HTML for supported sites
# Use for Amazon, Google, and other supported platforms when you want clean data
json_result = client.get("https://amazon.com/dp/B09V3KXJPB", autoparse: true).raw_body

段階的な切り替え

常に最も低コストの方法から始め、ブロックされた場合にのみ段階的に切り替えてください。

def scrape_with_escalation(client, url)
  tiers = [
    {},
    { render: true },
    { premium: true },
    { premium: true, render: true },
    { ultra_premium: true },
  ]

  tiers.each do |params|
    result = client.get(url, **params).raw_body
    return result if result&.include?("<html")
  end

  nil
end

非同期ジョブ(バッチ向け)

SDK は同期処理のため、各 client.get はレスポンスが届くまでブロックします(最大 70 秒)。 20 件以上の URL では、REST エンドポイント経由で非同期ジョブを送信してください。

require "net/http"
require "json"

API_KEY = ENV["SCRAPERAPI_API_KEY"]

def submit_job(url, api_params = {})
  uri = URI("https://async.scraperapi.com/jobs")
  payload = { apiKey: API_KEY, url: url, apiParams: api_params }
  response = Net::HTTP.post(uri, payload.to_json, "Content-Type" => "application/json")
  JSON.parse(response.body) # { "id" => "...", "statusUrl" => "..." }
end

def poll_job(job, max_wait: 120, interval: 5)
  deadline = Time.now + max_wait
  while Time.now < deadline
    uri = URI(job["statusUrl"])
    data = JSON.parse(Net::HTTP.get(uri))
    return data.dig("response", "body") if data["status"] == "finished"
    raise "Job #{job['id']} failed" if data["status"] == "failed"
    sleep interval
  end
  raise "Job #{job['id']} timed out"
end

# Submit all URLs, then collect results
urls = ["https://example.com/page1", "https://example.com/page2"]
jobs = urls.map { |u| submit_job(u) }
results = jobs.map { |j| poll_job(j) }

構造化データエンドポイント

対応プラットフォームでは、HTML を解析せずにクリーンな JSON を取得できる構造化エンドポイントを使用してください。

require "net/http"
require "json"

def structured_get(vertical, params = {})
  query = URI.encode_www_form({ api_key: API_KEY }.merge(params))
  uri = URI("https://api.scraperapi.com/structured/#{vertical}?#{query}")
  response = Net::HTTP.get_response(uri)
  raise "Error #{response.code}" unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body)
end

# Google SERP
results = structured_get("google/search", { query: "ruby web scraping" })

# Amazon product details
product = structured_get("amazon/product", { asin: "B09V3KXJPB" })

# eBay search
listings = structured_get("ebay/search", { query: "mechanical keyboard" })

エラー処理

SDK は HTTP エラー時に例外を発生させます。ステータスコードを確認して適切な対応を判断してください。

def safe_scrape(client, url, params = {})
  client.get(url, **params).raw_body
rescue => e
  status = e.respond_to?(:response) ? e.response&.code&.to_i : nil
  case status
  when 401 then raise "Invalid API key — check SCRAPERAPI_API_KEY"
  when 403 then raise "Blocked or out of credits — try premium: true or ultra_premium: true"
  when 429 then raise "Rate limit hit — reduce concurrency or switch to async"
  when 500, 503 then raise "Transient error — retry with exponential backoff"
  else raise
  end
end

ステータスコードの参照:200 成功、401 無効なキー、403 ブロック/クレジット不足、404 対象が見つからない、 429 レート制限、500/503 一時的なエラー(課金されません。安全に再試行できます)。

クレジットコストの参照

リクエストタイプクレジット
標準1
render: true10
premium: true10
premium: true, render: true25
ultra_premium: true30
ultra_premium: true, render: true75

ドキュメント

コメント