# ウェブを検索し、ソースリンクを保存

1つのGoogle検索を実行します。 クエリと使用量と一緒に、結果の順序で一意のソースリンクを保存します。

キャニシニカル参照: https://flashdata.dev/ja/docs/guides/web-search-recipe
レビュー: FlashData による 2026-11-05

<a id="prepare"></a>

## はじめる前に

google_searchの許可と利用可能なクレジットでキーを使用してください。 Python 3.10+ とリクエスト、Bash と cURL 7.76+ と jq+ を選択します。 Windowsでは、BashパスのGit Bashを使用します。

- [API キーを取得する](https://flashdata.dev/app/api-keys)
- [エージェントトライアルアクセス](https://flashdata.dev/ja/docs/guides/agent-access/reference.md)
- [クレジットと価格設定](https://flashdata.dev/ja/docs/guides/credits-and-billing/reference.md)

<a id="input"></a>

## 1. クエリの準備

Web-search フォルダーを作成します。 そこでrequest.jsonを保存し、そのフォルダのターミナルを開きます。 この例では、最大5つの有機結果が要求されます。 1つの新しい実行では、1つの請求可能なクエリを提出します。

### web-search/request.json

```json
{
  "source": "google_search",
  "query": "battery recycling research",
  "params": {
    "num": 5
  }
}
```


<a id="run"></a>

## 2. スクリプトを保存して実行する

1つのバージョンを選択し、request.jsonの横にあるスクリプトを保存します。 FLASHDATA_API_KEY を読み込み、またはキーを表示せずにプロンプトを表示します。 エージェントは、その秘密ストアから環境変数を供給する必要があります。

出力フォルダとしてsearch-001で実行します。 スクリプトは、送信前にリクエストを正確に保存します。 同じフォルダで再び実行すると、保存された応答がAPIを呼び出すことなく読み込まれます。

### Python

#### Python環境にインストール

```bash
python -m pip install requests
```

#### web-search/search.py

```python
import argparse
import getpass
import json
import os
from datetime import datetime, timezone
from pathlib import Path

import requests

parser = argparse.ArgumentParser()
parser.add_argument("folder", help="New output folder, or an existing saved search")
out = Path(parser.parse_args().folder)

if not out.exists():
    body = Path("request.json").read_bytes()
    request = json.loads(body)
    if not isinstance(request, dict) or request.get("source") != "google_search" or not request.get("query"):
        raise SystemExit("request.json must contain google_search and a query")
    key = os.environ.get("FLASHDATA_API_KEY") or getpass.getpass("FlashData API key: ")
    if not key.strip():
        raise SystemExit("An API key is required")
    out.mkdir()  # A concurrent run cannot submit into the same folder.
    (out / "request.json").write_bytes(body)
    (out / "requested-at.txt").write_text(
        datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), encoding="utf-8"
    )
    try:
        response = requests.post(
            "https://data.flashdata.dev/v1/queries/realtime",
            headers={"X-API-Key": key, "Content-Type": "application/json",
                     "Accept": "application/json"},
            data=body, timeout=120, allow_redirects=False,
        )
    except requests.RequestException:
        raise SystemExit(f"Request interrupted. Keep {out} and check History before retrying.")
    (out / "result.json").write_bytes(response.content)
    (out / "response-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8"
    )
    (out / "http-status.txt").write_text(str(response.status_code), encoding="utf-8")
else:
    print(f"Reading saved response from {out}; no API call.")

if not (out / "http-status.txt").exists():
    raise SystemExit("Incomplete attempt. Keep the folder and check History before retrying.")
status = (out / "http-status.txt").read_text().strip()
if status != "200":
    raise SystemExit(f"HTTP {status}: inspect {out}/result.json and response-headers.txt")

data = json.loads((out / "result.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "google_search" or data.get("status") != "done":
    raise SystemExit("Search did not finish successfully; inspect result.json")
pages = data.get("results")
if not isinstance(pages, list) or any(
    not isinstance(page, dict) or not isinstance(page.get("organic"), list) for page in pages
):
    raise SystemExit("Expected results[].organic arrays; inspect result.json")

sources, seen = [], set()
for page in pages:
    for row in page["organic"]:
        if not isinstance(row, dict):
            raise SystemExit("Expected organic result objects; inspect result.json")
        url = row.get("link")
        if isinstance(url, str) and url.strip() and url not in seen:
            seen.add(url)
            sources.append({field: row.get(field) for field in ("title", "link", "snippet")})
record = {
    "request": json.loads((out / "request.json").read_bytes()),
    "requested_at": (out / "requested-at.txt").read_text().strip(),
    "usage": data.get("usage"), "source_count": len(sources), "result_file": "result.json",
}
for filename, value in (("sources.json", sources), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {len(sources)} sources to {out}/sources.json")
```

#### ウェブ検索から実行する/

```bash
python search.py search-001
```


### Bash

#### ツールをチェック

```bash
curl --version
jq --version
```

#### web-search/search.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash search.sh OUTPUT_FOLDER}"

if [[ ! -e "$out" ]]; then
  jq -e '.source == "google_search" and (.query | type == "string" and length > 0)' \
    request.json > /dev/null
  if [[ -z "${FLASHDATA_API_KEY:-}" ]]; then
    read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
    printf '\n'
  fi
  : "${FLASHDATA_API_KEY:?An API key is required}"
  mkdir -- "$out"
  cp request.json "$out/request.json"
  date -u +'%Y-%m-%dT%H:%M:%SZ' > "$out/requested-at.txt"
  curl --fail-with-body --silent --show-error --max-time 120 \
    --request POST 'https://data.flashdata.dev/v1/queries/realtime' \
    --header "X-API-Key: $FLASHDATA_API_KEY" \
    --header 'Content-Type: application/json' --header 'Accept: application/json' \
    --data-binary "@$out/request.json" \
    --dump-header "$out/response-headers.txt" --output "$out/result.json" \
    --write-out '%{http_code}' > "$out/http-status.txt" || {
      printf 'Request failed. Keep %s and inspect its saved files before retrying.\n' "$out" >&2
      exit 1
    }
else
  printf 'Reading saved response from %s; no API call.\n' "$out"
fi

if [[ ! -f "$out/http-status.txt" ]] || [[ "$(cat "$out/http-status.txt")" != 200 ]]; then
  printf 'Incomplete or failed attempt. Inspect the saved files and History before retrying.\n' >&2
  exit 1
fi
sources=$(jq -e '
  if .source != "google_search" or .status != "done" or (.results | type) != "array"
  then error("Expected a successful google_search response") else . end
  | [.results[] | if (.organic | type) != "array"
      then error("Expected an organic array") else .organic[] end
      | if type != "object" then error("Expected an organic result object") else . end]
  | reduce .[] as $row ({seen: {}, sources: []};
      if ($row.link | type) != "string" then .
      elif ($row.link | test("\\S")) == false or .seen[$row.link] then .
      else .seen[$row.link] = true | .sources += [$row | {title, link, snippet}] end)
  | .sources' "$out/result.json")
printf '%s\n' "$sources" > "$out/sources.json"
jq --slurpfile request "$out/request.json" --slurpfile sources "$out/sources.json" \
  --arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
  '{request: $request[0], requested_at: $requested_at, usage,
    source_count: ($sources[0] | length), result_file: "result.json"}' \
  "$out/result.json" > "$out/record.json"
printf 'Saved %s sources to %s/sources.json\n' "$(jq length "$out/sources.json")" "$out"
```

#### ウェブ検索から実行する/

```bash
bash search.sh search-001
```



<a id="output"></a>

## 3. 保存されたソースを読みます

search-001/sources.json.に保存されたNソースを成功プリント 配列は、Google の返された順序で各正確なリンクの最初の発生を保ちます。 使用可能なリンクのない行は省略されます。 欠落したタイトルまたはスニペットの値は、nullのままです。

record.jsonは、送信されたクエリ、リクエスト時間、および返された使用量を含みます。 result.jsonをフル応答として保持します。 これらのファイルを読むことはローカルです。空のソース配列は有効な結果です。

### Python

#### 両方のファイルを読む

```bash
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.json
```


### Bash

#### 両方のファイルを読む

```bash
cat search-001/sources.json
cat search-001/record.json
```



<a id="expected"></a>

### 出力例

イラスト sources.json; ライブタイトル、リンク、スニペットとカウントは異なります。 回答の証拠としてスニペットを使用する前にリンクされたページを読んでください。

#### web-search/search-001/sources.json

```json
[
  {
    "title": "Battery recycling research",
    "link": "https://example.org/recycling",
    "snippet": "An example search excerpt."
  }
]
```


<a id="adapt"></a>

## より集中したクエリを試す

ドメインにフォーカスするには、以下の例にrequest.jsonのクエリを変更します。 新規クエリの出力フォルダを選択します。search-001は常に元の保存リクエストを参照します。

### web-search/request.json

```json
{
  "source": "google_search",
  "query": "site:energy.gov battery recycling research",
  "params": {
    "num": 5
  }
}
```

### Python

#### 新規問い合わせ・別の請求

```bash
python search.py search-002
```


### Bash

#### 新規問い合わせ・別の請求

```bash
bash search.sh search-002
```


- [パラメータ検索](https://flashdata.dev/ja/docs/sources/google_search/reference.md)
- [Google Searchベストプラクティス](https://flashdata.dev/ja/docs/guides/google-search-guide/reference.md)

<a id="recover"></a>

## 検索が注意を必要とする場合

| 何が起こったのか | 対処方法 |
| --- | --- |
| 401 / 403 / 402 | それぞれキー、google_searchのパーミッションと残高を確認してください。 この試みを続けてください。新しい出力フォルダを、再度送信する準備が整ったらのみ使用してください。 |
| 429 | response-headers.txt で Retry-After を読み、待ちます。 スクリプトは自動的に再試行しません。 |
| タイムアウト、5xx または不完全なフォルダー | 保存したファイルを保存し、別の試みを作成する前に History を確認してください。 同じフォルダを再実行すると、新しいリクエストは発生しません。 |
| 無効なJSON、失敗した状態または予期しない分野 | ソースを抽出する前に result.json を調べます。 無効な応答は、空の成功した検索として扱われるべきではありません。 |
| 有用な情報源はありません | 保存されたクエリーを確認します。 より具体的にするか、または過度に狭いフィルターを取除いて下さい、そして別の照会のための新しいホールダーを選んで下さい。 |

### Python

inspect_search.pyをWeb-search/で保存して実行します。

#### web-search/inspect_search.py

```python
from pathlib import Path

for name in ("http-status.txt", "response-headers.txt", "result.json"):
    path = Path("search-001") / name
    print(f"--- {name} ---")
    print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")
```

#### 現地で探す

```bash
python inspect_search.py
```


### Bash

#### 現地で探す

```bash
for name in http-status.txt response-headers.txt result.json; do
  printf '\n--- %s ---\n' "$name"
  if [[ -f "search-001/$name" ]]; then cat "search-001/$name"; else printf 'Not saved\n'; fi
done
```


- [リクエスト履歴](https://flashdata.dev/app/jobs)
- [エラーとステータスコード](https://flashdata.dev/ja/docs/errors/reference.md)
- [アプリケーションの検索をビルドする](https://flashdata.dev/ja/docs/guides/search-in-an-app/reference.md)
