> ## 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.

# Olostep NodeJS SDK

> Webからデータを検索、抽出、構造化するための公式NodeJS SDK

**NPMパッケージ**: [olostep](https://www.npmjs.com/package/olostep)

## はじめに

```bash theme={null}
npm install olostep
```

<CodeGroup>
  ```ts camelCase theme={null}
  import Olostep from 'olostep';

  const client = new Olostep({apiKey: process.env.OLOSTEP_API_KEY});

  // 最小限のスクレイピング例
  const result = await client.scrapes.create('https://example.com');
  console.log(result.id, result.html_content);
  ```

  ```ts snake_case theme={null}
  import Olostep from 'olostep';

  const client = new Olostep({api_key: process.env.OLOSTEP_API_KEY});

  // 最小限のスクレイピング例
  const result = await client.scrapes.create('https://example.com');
  console.log(result.id, result.html_content);
  ```
</CodeGroup>

<Note>
  NodeJS SDKはすべてのパラメータに対して**camelCase**と**snake\_case**の両方を受け入れます。AIエージェント用に構築する場合は、APIのネイティブフィールド名に一致する**snake\_case**を使用してください。
</Note>

## 使用方法

### スクレイピング

様々なオプションで単一のURLをスクレイピングします:

<CodeGroup>
  ```ts camelCase theme={null}
  import Olostep, {Format} from 'olostep';

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

  // シンプルなスクレイピング
  const scrape = await client.scrapes.create('https://example.com');

  // 複数のフォーマットで
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    formats: [Format.HTML, Format.MARKDOWN, Format.TEXT],
    waitBeforeScraping: 1000,
    removeImages: true
  });

  // コンテンツにアクセス
  console.log(scrape.html_content);
  console.log(scrape.markdown_content);

  // IDでスクレイプを取得
  const fetched = await client.scrapes.get(scrape.id);
  ```

  ```ts snake_case theme={null}
  import Olostep, {Format} from 'olostep';

  const client = new Olostep({api_key: 'your_api_key'});

  // シンプルなスクレイピング
  const scrape = await client.scrapes.create('https://example.com');

  // 複数のフォーマットで
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    formats: [Format.HTML, Format.MARKDOWN, Format.TEXT],
    wait_before_scraping: 1000,
    remove_images: true
  });

  // コンテンツにアクセス
  console.log(scrape.html_content);
  console.log(scrape.markdown_content);

  // IDでスクレイプを取得
  const fetched = await client.scrapes.get(scrape.id);
  ```
</CodeGroup>

### バッチ処理

複数のURLを一度に処理します:

<CodeGroup>
  ```ts camelCase theme={null}
  // URL文字列を使用（カスタムIDは自動生成）
  const batch = await client.batches.create([
    'https://example.com',
    'https://example.org',
    'https://example.net'
  ]);

  // または明示的なカスタムIDを使用
  const batch = await client.batches.create([
    {url: 'https://example.com', customId: 'site-1'},
    {url: 'https://example.org', customId: 'site-2'}
  ]);

  console.log(`Batch ${batch.id} created with ${batch.total_urls} URLs`);

  // 完了を待つ
  await batch.waitTillDone({
    checkEveryNSecs: 5,
    timeoutSeconds: 120
  });

  // バッチ情報を取得
  const info = await batch.info();
  console.log(info);

  // 個別の結果をストリーム
  for await (const item of batch.items()) {
    console.log(item.custom_id);
  }
  ```

  ```ts snake_case theme={null}
  // URL文字列を使用（カスタムIDは自動生成）
  const batch = await client.batches.create([
    'https://example.com',
    'https://example.org',
    'https://example.net'
  ]);

  // または明示的なカスタムIDを使用
  const batch = await client.batches.create([
    {url: 'https://example.com', custom_id: 'site-1'},
    {url: 'https://example.org', custom_id: 'site-2'}
  ]);

  console.log(`Batch ${batch.id} created with ${batch.total_urls} URLs`);

  // 完了を待つ
  await batch.waitTillDone({
    check_every_n_secs: 5,
    timeout_seconds: 120
  });

  // バッチ情報を取得
  const info = await batch.info();
  console.log(info);

  // 個別の結果をストリーム
  for await (const item of batch.items()) {
    console.log(item.custom_id);
  }
  ```
</CodeGroup>

### クロール

ウェブサイト全体をクロールします:

<CodeGroup>
  ```ts camelCase theme={null}
  const crawl = await client.crawls.create({
    url: 'https://example.com',
    maxPages: 100,
    maxDepth: 3,
    includeUrls: ['*/blog/*'],
    excludeUrls: ['*/admin/*']
  });

  console.log(`Crawl ${crawl.id} started`);

  // 完了を待つ
  await crawl.waitTillDone({
    checkEveryNSecs: 10,
    timeoutSeconds: 300
  });

  // クロール情報を取得
  const info = await crawl.info();
  console.log(`Crawled ${info.pages_crawled} pages`);

  // クロールしたページをストリーム
  for await (const page of crawl.pages()) {
    console.log(page.url, page.status_code);
  }
  ```

  ```ts snake_case theme={null}
  const crawl = await client.crawls.create({
    url: 'https://example.com',
    max_pages: 100,
    max_depth: 3,
    include_urls: ['*/blog/*'],
    exclude_urls: ['*/admin/*']
  });

  console.log(`Crawl ${crawl.id} started`);

  // 完了を待つ
  await crawl.waitTillDone({
    check_every_n_secs: 10,
    timeout_seconds: 300
  });

  // クロール情報を取得
  const info = await crawl.info();
  console.log(`Crawled ${info.pages_crawled} pages`);

  // クロールしたページをストリーム
  for await (const page of crawl.pages()) {
    console.log(page.url, page.status_code);
  }
  ```
</CodeGroup>

### サイトマッピング

ウェブサイトからURLのサイトマップを生成します:

<CodeGroup>
  ```ts camelCase theme={null}
  const map = await client.maps.create({
    url: 'https://example.com',
    topN: 100,
    includeSubdomain: true,
    searchQuery: 'blog posts'
  });

  console.log(`Map ${map.id} created`);

  // URLをストリーム
  for await (const url of map.urls()) {
    console.log(url);
  }

  // マップ情報を取得
  const info = await map.info();
  ```

  ```ts snake_case theme={null}
  const map = await client.maps.create({
    url: 'https://example.com',
    top_n: 100,
    include_subdomain: true,
    search_query: 'blog posts'
  });

  console.log(`Map ${map.id} created`);

  // URLをストリーム
  for await (const url of map.urls()) {
    console.log(url);
  }

  // マップ情報を取得
  const info = await map.info();
  ```
</CodeGroup>

### AI駆動の回答

AIを使用してウェブページから回答を取得します:

<CodeGroup>
  ```ts camelCase theme={null}
  import Olostep from 'olostep';

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

  // シンプルなタスク: 文字列を直接渡す
  const answer = await client.answers.create(
    'What is the main topic of https://example.com?'
  );
  console.log(answer.answer);
  console.log(answer.sources);

  // 構造化されたJSON出力で
  const structured = await client.answers.create({
    task: 'Extract all product names and prices from https://example.com',
    jsonFormat: {
      products: [{name: '', price: ''}]
    }
  });
  console.log(structured.json_content);

  // 以前に作成された回答をIDで取得
  const fetched = await client.answers.get(answer.id);
  console.log(fetched.answer);
  ```

  ```ts snake_case theme={null}
  import Olostep from 'olostep';

  const client = new Olostep({api_key: 'your_api_key'});

  // シンプルなタスク: 文字列を直接渡す
  const answer = await client.answers.create(
    'What is the main topic of https://example.com?'
  );
  console.log(answer.answer);
  console.log(answer.sources);

  // 構造化されたJSON出力で
  const structured = await client.answers.create({
    task: 'Extract all product names and prices from https://example.com',
    json_format: {
      products: [{name: '', price: ''}]
    }
  });
  console.log(structured.json_content);

  // 以前に作成された回答をIDで取得
  const fetched = await client.answers.get(answer.id);
  console.log(fetched.answer);
  ```
</CodeGroup>

### コンテンツの取得

以前にスクレイプしたコンテンツを取得します:

```ts theme={null}
// 特定のフォーマットでコンテンツを取得
const content = await client.retrieve(retrieveId, Format.MARKDOWN);
console.log(content.markdown_content);

// 複数のフォーマット
const content = await client.retrieve(retrieveId, [
  Format.HTML,
  Format.MARKDOWN
]);
```

### 高度なオプション

#### カスタムアクション

スクレイピング前にブラウザアクションを実行します:

```ts theme={null}
const scrape = await client.scrapes.create({
  url: 'https://example.com',
  actions: [
    {type: 'wait', milliseconds: 2000},
    {type: 'click', selector: '#load-more'},
    {type: 'scroll', distance: 1000},
    {type: 'fill_input', selector: '#search', value: 'query'}
  ]
});
```

#### 地理的位置

事前定義された国コードまたは有効な国コード文字列を使用して、異なる国からスクレイプします:

<CodeGroup>
  ```ts camelCase theme={null}
  import Olostep, {Country} from 'olostep';

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

  // 事前定義された列挙値を使用（US, DE, FR, GB, SG）
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    country: Country.DE  // ドイツ
  });

  // または有効な国コードを文字列として使用
  const scrape2 = await client.scrapes.create({
    url: 'https://example.com',
    country: 'jp'  // 日本
  });
  ```

  ```ts snake_case theme={null}
  import Olostep, {Country} from 'olostep';

  const client = new Olostep({api_key: 'your_api_key'});

  // 事前定義された列挙値を使用（US, DE, FR, GB, SG）
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    country: Country.DE  // ドイツ
  });

  // または有効な国コードを文字列として使用
  const scrape2 = await client.scrapes.create({
    url: 'https://example.com',
    country: 'jp'  // 日本
  });
  ```
</CodeGroup>

#### キャッシング

デフォルトでは、すべてのスクレイプリクエストは新しいページを取得します（`max_age: 0`）。`maxAge`を渡して、同じパラメータで最近の結果を再利用し、応答時間を改善します。値は**秒**で、最大は7日間（`604800`）です。詳細は[キャッシング](/features/scrapes#caching)を参照してください。

<CodeGroup>
  ```ts camelCase theme={null}
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    formats: ['markdown'],
    maxAge: 86400 // 最大1日前の結果を受け入れる
  });
  ```

  ```ts snake_case theme={null}
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    formats: ['markdown'],
    max_age: 86400 // 最大1日前の結果を受け入れる
  });
  ```
</CodeGroup>

#### LLM抽出

LLMを使用して構造化データを抽出します:

<CodeGroup>
  ```ts camelCase theme={null}
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    llmExtract: {
      schema: {
        title: 'string',
        price: 'number',
        description: 'string'
      },
      prompt: 'Extract product information from this page'
    }
  });
  ```

  ```ts snake_case theme={null}
  const scrape = await client.scrapes.create({
    url: 'https://example.com',
    llm_extract: {
      schema: {
        title: 'string',
        price: 'number',
        description: 'string'
      },
      prompt: 'Extract product information from this page'
    }
  });
  ```
</CodeGroup>

### クライアント設定

<CodeGroup>
  ```ts camelCase theme={null}
  import Olostep from 'olostep';

  const client = new Olostep({
    apiKey: 'your_api_key',
    apiBaseUrl: 'https://api.olostep.com/v1',  // オプション
    timeoutMs: 150000,  // 150秒（オプション）
    retry: {
      maxRetries: 3,
      initialDelayMs: 1000
    },
    userAgent: 'MyApp/1.0'  // オプション
  });
  ```

  ```ts snake_case theme={null}
  import Olostep from 'olostep';

  const client = new Olostep({
    api_key: 'your_api_key',
    api_base_url: 'https://api.olostep.com/v1',  // オプション
    timeout_ms: 150000,  // 150秒（オプション）
    retry: {
      max_retries: 3,
      initial_delay_ms: 1000
    },
    user_agent: 'MyApp/1.0'  // オプション
  });
  ```
</CodeGroup>

### 機能のハイライト

* フルTypeScriptサポートの非同期ファーストクライアント。
* TypeScriptの列挙型とインターフェース（Formats, Countries, Actionsなど）を使用した型安全な入力。
* 簡潔な呼び出し（`client.scrapes.create()`）と明示的なメソッド（`client.scrapes.get()`）を備えたリッチなリソースネームスペース。
* リトライ、タイムアウト、JSONデコードを備えた共有トランスポートレイヤー。
* 包括的なエラーハイアラーキー。
