scrapfly-extraction について
scrapfly-extractionは、Scrapfly Extraction APIでHTML、Markdown、テキストから構造化データを抽出するスキルです。プロンプト、事前学習済みモデル、テンプレートを利用できます。
主な機能
- 01プロンプトによる構造化データ抽出
- 02一般的なデータ向けの事前学習済みモデル
- 03再利用可能なテンプレートとインラインテンプレート
- 04スクレイピング時のデータ抽出
- 05文書内容への質問応答
活用シーン
- 01商品や記事の情報抽出
- 02レビューや不動産リストの解析
- 03類似ページへの統一ルール適用
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ scrapfly/ skills --skill scrapfly-extractionインストール後、Claude Code で/scrapfly-extractionを入力して読み込まれたか確認します。
詳細
Scrapfly 抽出
Scrapfly Extraction API を使用して、LLM プロンプト、事前学習済み AI モデル、またはカスタム抽出テンプレートで、HTML、Markdown、テキストから構造化データを抽出します。
使用する場面
- Web ページのコンテンツから構造化データを抽出する
- 自然言語のプロンプトで、ドキュメントから特定の情報を取得する
- 自動 AI モデルで、商品、記事、レビュー、不動産のデータを抽出する
- カスタムテンプレートで、HTML/Markdown を構造化形式に解析する
- ドキュメントの内容について質問し、AI による回答を得る
セットアップ
pip install scrapfly-sdk
API キーは環境変数 SCRAPFLY_API_KEY を使用して指定するか、クライアントに直接渡す必要があります。
API リファレンス
エンドポイント: POST https://api.scrapfly.io/extraction
ScrapflyClient
from scrapfly import ScrapflyClient, ExtractionConfig
import os
client = ScrapflyClient(key=os.environ["SCRAPFLY_API_KEY"])
ExtractionConfig のパラメーター
| パラメーター | 型 | デフォルト | 説明 |
|---|---|---|---|
body | str | 必須 | 抽出元のドキュメントコンテンツ |
content_type | str | 必須 | 入力形式:"text/html"、"text/markdown"、"text/plain"、"text/xml" |
url | str | None | HTML 内の相対リンクを解決するためのベース URL |
charset | str | None | ドキュメントのエンコーディング(省略時は自動検出) |
extraction_prompt | str | None | LLM 抽出用の自然言語による指示 |
extraction_model | str | None | 事前学習済みモデル:"product"、"article"、"review_list"、"real_estate_listing" |
extraction_template | str | None | カスタムテンプレート名またはインラインのテンプレート定義 |
timeout | int | None | 処理タイムアウト(秒)(60-155) |
webhook_name | str | None | 非同期処理用の Webhook 名 |
次のいずれか1つを必ず指定してください: extraction_prompt、extraction_model、または extraction_template。
3つの抽出方法
1. LLM プロンプトによる抽出
抽出するデータを自然言語で記述します。AI がコンテンツを解釈し、構造化された結果を返します。
2. 自動 AI モデル
一般的なデータ型に対応する事前学習済みモデルです。品質スコア付きの標準化されたスキーマを返します。
"article"- ニュース/ブログ記事(タイトル、著者、日付、コンテンツなど)"event"- イベント(名前、日付、場所、説明など)"food_recipe"- レシピ(材料、手順、分量など)"hotel"- 単一のホテル/宿泊施設(名前、設備、評価など)"hotel_listing"- ホテルの検索結果/一覧"job_listing"- 求人の検索結果/一覧"job_posting"- 単一の求人(職種名、会社、給与、説明など)"organization"- 会社/組織(名前、連絡先、説明など)"product"- EC 商品(名前、価格、説明、画像など)"product_listing"- 商品の検索結果/カテゴリ一覧"real_estate_property"- 単一の不動産物件(価格、住所、特徴など)"real_estate_property_listing"- 不動産物件の検索結果/一覧"review_list"- レビューの一覧(投稿者、評価、テキスト、日付など)"search_engine_results"- SERP データ(検索結果、スニペットなど)"social_media_post"- ソーシャルメディアの投稿(投稿者、コンテンツ、エンゲージメントなど)"software"- ソフトウェア/アプリ(名前、説明、料金など)"stock"- 株式/市場データ"vehicle_ad"- 単一の車両掲載情報"vehicle_ad_listing"- 車両の検索結果/一覧
3. カスタムテンプレート
類似したページを一貫した方法で解析するための、構造化された抽出ルールです。インライン(JSON オブジェクト)で定義するか、Scrapfly に保存してスラッグで参照できます。
保存済みテンプレート(スラッグで参照)
Scrapfly ダッシュボード(Extraction API → Templates)にテンプレートを保存している場合は、スラッグを通常の文字列として渡します。プラットフォームは現在公開中のバージョンを解決して適用します。
result = client.extract(ExtractionConfig(
body=html_content,
content_type="text/html",
url="https://example.com/product/1",
extraction_template="product-card",
))
保存済みテンプレートでは、次の機能を利用できます。
- 公開ポインターが独立した完全なバージョン履歴(新しいバージョンをアトミックに公開でき、いつでもロールバックできます)。
- ダッシュボードで設定する任意の URL スコープ(
match_domain/match_path)。一致しない URL に対する呼び出しはERR::EXTRACTION::TEMPLATE_URL_MISMATCHを返します。 - TTL が 60 秒の読み取り時キャッシュ。新しく公開したバージョンは 1 分以内に有効になり、クライアントの再デプロイは不要です。
スラッグは、小文字の英字、数字、ハイフンで構成された 3~128 文字の形式です。
インラインテンプレート
一度だけ抽出する場合は、Python の dict を渡します。単発のスクリプトや、呼び出しごとに異なるテンプレートを使用する場合に便利です。
extraction_template = {
"source": "html",
"selectors": [
{
"name": "title",
"query": "h3.product-title::text",
"type": "css",
"formatters": [
{
"name": "uppercase"
}
],
},
{
"name": "description",
"query": "p.product-description::text",
"type": "css"
},
{
"extractor": {
"name": "price"
},
"name": "price",
"query": ".product-price::text",
"type": "css"
},
{
"name": "variants",
"query": "div.variants",
"type": "css",
"nested": [
{
"name": "name",
"query": "//a[@data-variant-id]/@data-variant-id",
"type": "xpath",
"multiple": True,
},
{
"name": "link",
"query": "//a[@data-variant-id]/@href",
"type": "xpath",
"multiple": True,
},
]
},
{
"name": "reviews",
"query": "div.review>p::text",
"type": "css",
"multiple": True,
}
]
}
例
HTML から LLM プロンプトで抽出する
from scrapfly import ScrapflyClient, ExtractionConfig
import os
client = ScrapflyClient(key=os.environ["SCRAPFLY_API_KEY"])
html_content = "<html><body><h1>iPhone 15</h1><span class='price'>$999</span><p>Latest Apple smartphone</p></body></html>"
result = client.extract(ExtractionConfig(
body=html_content,
content_type="text/html",
extraction_prompt="Extract the product name, price, and description as JSON",
))
# result
result.extraction_result['data']
# or
print(result.data)
# result content_type
result.extraction_result['content_type']
# or
print(result.content_type)
Markdown から LLM プロンプトで抽出する
markdown_content = """
# Best Restaurants in NYC
1. **Le Bernardin** - French, $$$, 4.8 stars
2. **Peter Luger** - Steakhouse, $$$, 4.5 stars
3. **Di Fara Pizza** - Italian, $, 4.7 stars
"""
result = client.extract(ExtractionConfig(
body=markdown_content,
content_type="text/markdown",
extraction_prompt="Extract each restaurant as a JSON array with name, cuisine, price_range, and rating fields",
))
print(result.data)
自動 AI モデル:商品抽出
from scrapfly import ScrapflyClient, ExtractionConfig, ScrapeConfig
# First scrape the page, then extract
scrape_result = client.scrape(ScrapeConfig(url="https://web-scraping.dev/product/1"))
result = client.extract(ExtractionConfig(
body=scrape_result.content,
content_type="text/html",
url="https://web-scraping.dev/product/1",
extraction_model="product",
))
print(result.data)
# Returns: {"name": "...", "price": "...", "currency": "...", "description": "...", ...}
コンテンツについて質問する
result = client.extract(ExtractionConfig(
body=html_content,
content_type="text/html",
extraction_prompt="What is the most expensive item on this page and how much does it cost?",
))
print(result.data)
スクレイピングと抽出を 1 つのフローで行う
from scrapfly import ScrapflyClient, ScrapeConfig, ExtractionConfig
import os
client = ScrapflyClient(key=os.environ["SCRAPFLY_API_KEY"])
# Step 1: Scrape the page
scrape_result = client.scrape(ScrapeConfig(
url="https://web-scraping.dev/product/1",
format="markdown",
))
# Step 2: Extract structured data from the content
extraction_result = client.extract(ExtractionConfig(
body=scrape_result.content,
content_type="text/markdown",
extraction_prompt="Extract all products as a JSON array with fields: name, price, availability",
))
print(extraction_result.data)
Scrape API でインライン抽出する
スクレイプリクエスト内で直接データを抽出することもできます。
result = client.scrape(ScrapeConfig(
url="https://web-scraping.dev/product/1",
extraction_prompt="Extract the product name, price, and description as JSON",
))
# Extraction result is included in the scrape response
print(result.scrape_result["extracted_data"])
カスタム抽出テンプレート(インライン)
# First, scrape the web page to retrieve its HTML
api_response = client.scrape(scrape_config=ScrapeConfig(
url='https://web-scraping.dev/product/1',
render_js=True
))
html = api_response.content
# extraction template for HTML parsing instructions. It accepts the following:
# selectors: CSS, XPath, JMESPath, Regex, Nested (nesting multiple selector types)
# extractors: extracts commonly accessed data types: price, image, links, emails
# formatters: transforms the extracted data for common methods: lowercase, uppercase, datatime, etc.
# refer to the docs for more details: https://scrapfly.io/docs/extraction-api/rules-and-template#rules
extraction_template = {
"source": "html",
"selectors": [
{
"name": "title",
"query": "h3.product-title::text",
"type": "css",
"formatters": [
{
"name": "uppercase"
}
],
},
{
"name": "description",
"query": "p.product-description::text",
"type": "css"
},
{
"extractor": {
"name": "price"
},
"name": "price",
"query": ".product-price::text",
"type": "css"
},
{
"name": "variants",
"query": "div.variants",
"type": "css",
"nested": [
{
"name": "name",
"query": "//a[@data-variant-id]/@data-variant-id",
"type": "xpath",
"multiple": True,
},
{
"name": "link",
"query": "//a[@data-variant-id]/@href",
"type": "xpath",
"multiple": True,
},
]
},
{
"name": "reviews",
"query": "div.review>p::text",
"type": "css",
"multiple": True,
}
]
}
extraction_api_response = client.extract(
extraction_config=ExtractionConfig(
body=html, # pass the HTML content
content_type='text/html', # content data type
charset='utf-8', # passed content charset, use `auto` if you aren't sure
extraction_ephemeral_template=extraction_template # declared template defintion or template name saved on the dashboard
)
)
# extracted data
print(extraction_api_response.data)
# extracted data content_type
print(extraction_api_response.content_type)
エラー処理
from scrapfly.errors import ScrapflyError
try:
result = client.extract(ExtractionConfig(
body="<html><body><h1>iPhone 15</h1><span class='price'>$999</span><p>Latest Apple smartphone</p></body></html",
content_type="text/html",
extraction_prompt="Extract the product price",
))
print(result.data)
except ScrapflyError as e:
print(f"Extraction failed: {e.message}")
重要な注意事項
- リクエストごとに、抽出方法は
extraction_prompt、extraction_model、extraction_templateのいずれか 1 つだけ指定してください。 - LLM プロンプトでは、希望する出力形式(例:「JSON 形式」)を具体的に指定してください。
urlパラメーターは HTML 内の相対リンクを解決するのに役立ちますが、必須ではありません。- 大きなドキュメントでは、まずスクレイプの手順で
format="markdown"またはformat="text"を使用して、トークンの使用量を抑えることを検討してください。 - 自動 AI モデルは、抽出データと併せて品質指標を返します。
ScrapeConfigにextraction_promptまたはextraction_modelを追加すると、スクレイピング中にインラインで抽出することもできます。