> ## Documentation Index
> Fetch the complete documentation index at: https://docs.olostep.com/llms.txt
> Use this file to discover all available pages before exploring further.

# クロール

> URLをクロールしてすべてのサブページのコンテンツを取得する

Olostepの`/v1/crawls`エンドポイントを使用して、ウェブサイトをクロールし、すべてのページのコンテンツを取得できます。

* ウェブサイトをクロールし、すべてのサブページのコンテンツを取得（またはクロールの深さを制限）
* 特定のページをクロールするための特別なパターンを使用（例：`/blog/**`）
* クロール完了時に通知を受け取るために`webhook_url`を渡す
* 特定のページを見つけるための検索クエリと関連性でソート

APIの詳細については、[クロールエンドポイントAPIリファレンス](/api-reference/crawls/create)を参照してください。

## インストール

<CodeGroup>
  ```python Python theme={null}
  pip install olostep
  ```

  ```javascript Node theme={null}
  npm install olostep
  ```

  ```bash cURL theme={null}
  # curlはmacOS、Linux、Windowsでデフォルトで利用可能
  ```

  ```javascript Node (API) theme={null}
  npm install node-fetch
  ```

  ```bash Python (API) theme={null}
  pip install requests
  ```
</CodeGroup>

## クロールを開始

開始URL、含める/除外するURLグロブ、`max_pages`を指定します。オプション：`max_depth`、`include_external`、`include_subdomain`、`search_query`、`top_n`、`webhook_url`、`timeout`。

<CodeGroup>
  ```python Python theme={null}
  from olostep import Olostep

  client = Olostep(api_key="YOUR_REAL_KEY")

  crawl = client.crawls.create(
      start_url="https://olostep.com",
      max_pages=100,
      include_urls=["/**"],
      exclude_urls=["/collections/**"],
      include_external=False,
  )

  print(crawl.id, crawl.status)
  ```

  ```js Node theme={null}
  import Olostep from 'olostep'

  const client = new Olostep({ apiKey: 'YOUR_REAL_KEY' })

  const crawl = await client.crawls.create({
    url: 'https://olostep.com',
    maxPages: 100,
    includeUrls: ['/**'],
    excludeUrls: ['/collections/**'],
    includeExternal: false,
  })

  console.log(crawl.id, crawl.status)
  ```

  ```bash cURL theme={null}
  curl -s -X POST "https://api.olostep.com/v1/crawls" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "start_url": "https://olostep.com",
      "max_pages": 100,
      "include_urls": ["/**"],
      "exclude_urls": ["/collections/**"]
    }'
  ```

  ```js Node (API) theme={null}
  const API_URL = 'https://api.olostep.com'
  const res = await fetch(`${API_URL}/v1/crawls`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>', 'Content-Type': 'application/json' },
    body: JSON.stringify({
      start_url: 'https://olostep.com',
      max_pages: 100,
      include_urls: ['/**'],
      exclude_urls: ['/collections/**']
    })
  })
  console.log(await res.json())
  ```

  ```python Python (API) theme={null}
  import time, json

  API_URL = 'https://api.olostep.com'
  API_KEY = '<YOUR_API_KEY>'
  HEADERS = { 
      'Content-Type': 'application/json',
      'Authorization': f'Bearer {API_KEY}' 
  }

  data = {
    "start_url": "https://olostep.com",
    "max_pages": 100,
    "include_urls": ["/**"],
    "exclude_urls": ["/collections/**"],
    "include_external": False
  }

  res = requests.post(f"{API_URL}/v1/crawls", headers=HEADERS, json=data)
  crawl = res.json()
  print(json.dumps(crawl, indent=2))
  ```
</CodeGroup>

Olostepではすべてがオブジェクトであるため、レスポンスとして`crawl`オブジェクトを受け取ります。`crawl`オブジェクトには、`id`や`status`などのプロパティがあり、これを使用してクロールを追跡できます。

## クロールのステータスを確認

`status`が`completed`になるまでクロールをポーリングして進捗を追跡します。

<CodeGroup>
  ```python Python theme={null}
  # 前のステップのcrawlオブジェクトを使用
  info = crawl.info()
  print(info.status, info.pages_count)

  # または完了するまで待つ
  crawl.wait_till_done(check_every_n_secs=5)
  ```

  ```js Node theme={null}
  // 前のステップのcrawlオブジェクトを使用
  const info = await crawl.info()
  console.log(info.status, info.pages_count)

  // または完了するまで待つ
  await crawl.waitTillDone({ checkEveryNSecs: 5 })
  ```

  ```bash cURL theme={null}
  curl -s -X GET "https://api.olostep.com/v1/crawls/<CRAWL_ID>" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```

  ```js Node (API) theme={null}
  const crawlId = '<CRAWL_ID>'
  const status = await fetch(`${API_URL}/v1/crawls/${crawlId}`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  }).then(r => r.json())
  console.log(status)
  ```

  ```python Python (API) theme={null}
  import time

  def get_crawl_info(crawl_id):
      return requests.get(f'{API_URL}/v1/crawls/{crawl_id}', headers=HEADERS).json()

  crawl_id = crawl['id']
  while True:
      info = get_crawl_info(crawl_id)
      print(info['status'], info.get('pages_count'))
      if info['status'] == 'completed':
          break
      time.sleep(5)
  ```
</CodeGroup>

または、クロール開始時に`webhook_url`を渡して、クロールが完了したときに通知を受け取ることができます。

## ページを一覧表示（カーソルでページネート/ストリーム）

`cursor`と`limit`を使用してページを取得し、繰り返し処理します。クロールが`in_progress`または`completed`の間に動作します。

<CodeGroup>
  ```python Python theme={null}
  # すべてのページを繰り返し処理（クロール完了を自動的に待機し、ページネーションを処理）
  for page in crawl.pages():
      print(page.url, page.retrieve_id)
  ```

  ```js Node theme={null}
  // すべてのページを繰り返し処理（クロール完了を自動的に待機し、ページネーションを処理）
  for await (const page of crawl.pages()) {
    console.log(page.url, page.retrieve_id)
  }
  ```

  ```bash cURL theme={null}
  curl -s -G "https://api.olostep.com/v1/crawls/<CRAWL_ID>/pages" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    --data-urlencode "cursor=0" \
    --data-urlencode "limit=10"
  ```

  ```js Node (API) theme={null}
  let cursor = 0
  while (true) {
    const pages = await fetch(`${API_URL}/v1/crawls/${crawlId}/pages?cursor=${cursor}&limit=10`, {
      headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
    }).then(r => r.json())
    pages.pages.forEach(p => console.log(p.url, p.retrieve_id))
    if (pages.cursor === undefined) break
    cursor = pages.cursor
  }
  ```

  ```python Python (API) theme={null}
  def get_pages(crawl_id, cursor=None, limit=10, search_query=None):
      params = { 
          'cursor': cursor, 
          'limit': limit
      }
      return requests.get(f'{API_URL}/v1/crawls/{crawl_id}/pages', headers=HEADERS, params=params).json()

  cursor = 0
  while True:
      page_batch = get_pages(crawl_id, cursor=cursor, limit=10)
      for page in page_batch['pages']:
          print(page['url'], page['retrieve_id'])
      if 'cursor' not in page_batch:
          break
      cursor = page_batch['cursor']
      time.sleep(5)
  ```
</CodeGroup>

## 検索クエリ（関連性の高い上位N件に制限）

開始時に`search_query`を使用し、オプションでリストを`search_query`でフィルタリングします。ページごとの探索を`top_n`で制限します。

<CodeGroup>
  ```python Python theme={null}
  from olostep import Olostep

  client = Olostep(api_key="YOUR_REAL_KEY")

  crawl = client.crawls.create(
      start_url="https://olostep.com",
      max_pages=100,
      include_urls=["/**"],
      search_query="contact us",
      top_n=5,
  )

  for page in crawl.pages(search_query="contact us"):
      print(page.url)
  ```

  ```js Node theme={null}
  import Olostep from 'olostep'

  const client = new Olostep({ apiKey: 'YOUR_REAL_KEY' })

  const crawl = await client.crawls.create({
    url: 'https://olostep.com',
    maxPages: 100,
    includeUrls: ['/**'],
    searchQuery: 'contact us',
    topN: 5,
  })

  for await (const page of crawl.pages()) {
    console.log(page.url)
  }
  ```

  ```bash cURL theme={null}
  curl -s -X POST "https://api.olostep.com/v1/crawls" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "start_url": "https://olostep.com",
      "max_pages": 100,
      "include_urls": ["/**"],
      "search_query": "contact us",
      "top_n": 5
    }'
  ```

  ```js Node (API) theme={null}
  await fetch(`${API_URL}/v1/crawls`, { method: 'POST', headers: { 'Authorization': 'Bearer <YOUR_API_KEY>', 'Content-Type': 'application/json' }, body: JSON.stringify({ start_url: 'https://olostep.com', max_pages: 100, include_urls: ['/**'], search_query: 'contact us', top_n: 5 }) })
  ```

  ```python Python (API) theme={null}
  data = {
    "start_url": "https://olostep.com",
    "max_pages": 100,
    "include_urls": ["/**"],
    "search_query": "contact us",
    "top_n": 5
  }
  crawl = requests.post(f'{API_URL}/v1/crawls', headers=HEADERS, json=data).json()
  pages = requests.get(f"{API_URL}/v1/crawls/{crawl['id']}/pages", headers=HEADERS, params={'search_query': 'contact us'}).json()
  print(len(pages['pages']))
  ```
</CodeGroup>

## コンテンツを取得

各ページの`retrieve_id`を使用して、`/v1/retrieve`から`html_content`および/または`markdown_content`を取得します。

<CodeGroup>
  ```python Python theme={null}
  # クロールされた各ページのコンテンツを取得
  for page in crawl.pages():
      content = page.retrieve(["markdown"])
      print(content.markdown_content)
  ```

  ```js Node theme={null}
  // クロールされた各ページのコンテンツを取得
  for await (const page of crawl.pages()) {
    const content = await client.retrieve.get(page.retrieve_id, ['markdown'])
    console.log(content.markdown_content)
  }
  ```

  ```bash cURL theme={null}
  curl -s -G "https://api.olostep.com/v1/retrieve" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    --data-urlencode "retrieve_id=<RETRIEVE_ID>"
  ```

  ```js Node (API) theme={null}
  const retrieved = await fetch(`${API_URL}/v1/retrieve?retrieve_id=<RETRIEVE_ID>`, { headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' } }).then(r => r.json())
  console.log(retrieved.markdown_content)
  ```

  ```python Python (API) theme={null}
  def retrieve_content(retrieve_id):
      return requests.get(f"{API_URL}/v1/retrieve", headers=HEADERS, params={"retrieve_id": retrieve_id}).json()

  for page in get_pages(crawl['id'], limit=5)['pages']:
      retrieved = retrieve_content(page['retrieve_id'])
      print(retrieved.get('markdown_content'))
  ```
</CodeGroup>

## 注意事項

* ページネーションはカーソルベースです。`cursor`がなくなるまでリクエストを繰り返します。
* `/v1/crawls/{crawl_id}/pages`のコンテンツフィールドは非推奨です。`/v1/retrieve`を使用してください。
* Webhooks: クロール完了時にPOSTを受け取るために`webhook_url`を設定します。

## 料金

クロールには、クロールされたページごとに1クレジットがかかります。
