コンテンツにスキップ
ログイン サインアップ

抽出ルール

BeautifulSoup、Cheerio、正規表現は不要です。どのCSSセレクタをどのJSONフィールドにマッピングするかをShifterに伝えるだけで、クリーンなJSONが返ってきます。

extract_rulesをURLエンコードされたJSONオブジェクトとして渡します。各キーは出力フィールド、各値はその抽出方法を記述します。

最小限の例:

{
"title": { "selector": "h1", "output": "text" }
}

URLエンコードして送信:

Terminal window
curl "https://scrape.shifter.io/v1?api_key=YOUR_API_KEY&url=https://example.com&extract_rules=%7B%22title%22%3A%7B%22selector%22%3A%22h1%22%2C%22output%22%3A%22text%22%7D%7D"
# {"title": "Example Domain"}
output戻り値
text要素のテキスト内容"Example Domain"
html内部HTML"<strong>Example</strong> Domain"
@<attr>属性値"@href""https://example.com/"

ルールオブジェクトにキーを追加します:

{
"title": { "selector": "h1", "output": "text" },
"description": { "selector": "meta[name=description]", "output": "@content" },
"canonical": { "selector": "link[rel=canonical]", "output": "@href" }
}

レスポンス:

{
"title": "Example Domain",
"description": "The example domain...",
"canonical": "https://example.com/"
}

リスト(検索結果、商品カード、テーブル行など)の場合は、type: "list"itemを指定する親要素でルールをラップします:

{
"products": {
"selector": "div.product",
"type": "list",
"item": {
"name": { "selector": "h2", "output": "text" },
"price": { "selector": ".price", "output": "text" },
"link": { "selector": "a.title", "output": "@href" }
}
}
}

レスポンス:

{
"products": [
{ "name": "Item A", "price": "$19.99", "link": "/item-a" },
{ "name": "Item B", "price": "$24.50", "link": "/item-b" }
]
}

すでにJSONを返すエンドポイント(ほとんどのREST API)の場合は、auto_parser=1を追加すると、本文をパースしてそのまま返します:

Terminal window
curl "https://scrape.shifter.io/v1?api_key=YOUR_API_KEY&url=https://api.example.com/products&auto_parser=1"
  • まずブラウザの開発者コンソールでセレクタをテストしてください: document.querySelector(...)
  • URLエンコードされたJSONを正しくエスケープしてください。ほとんどのHTTPクライアントは、ルールをパラメータオブジェクトとして渡す際に自動的にこれを行います。
  • ページ上にフィールドが存在しない場合、リクエストは失敗せずnullが返されます。