# 웹 검색 및 소스 링크 저장

하나의 Google 검색을 실행합니다. 결과 주문에 고유 한 소스 링크를 저장하고, 쿼리 및 사용과 함께.

Canonical 참고: https://flashdata.dev/ko/docs/guides/web-search-recipe
검토: 2026-11-05 FlashData

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

## 시작하기 전에

google_search 권한 및 사용 가능한 크레딧으로 키를 사용합니다. 제품 정보 Python 3.10+ 요청, 또는 Bash 으로 cURL 7.76+ 및 jq. Windows에서 Git Bash를 Bash 경로에 사용합니다.

- [API 키 받기](https://flashdata.dev/app/api-keys)
- [Agent 시험 접근](https://flashdata.dev/ko/docs/guides/agent-access/reference.md)
- [크레딧 및 가격](https://flashdata.dev/ko/docs/guides/credits-and-billing/reference.md)

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

## 1. 자주 묻는 질문

웹 검색 폴더를 만듭니다. 저장 request.json 거기, 그 폴더에 터미널을 엽니 다. 이 예제는 5 개의 유기 결과까지 요청합니다. 하나의 새로운 실행은 1 개의 청구 가능한 쿼리를 제출합니다.

### web-search/request.json

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


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

## 2. 저장하고 스크립트를 실행

하나의 버전을 선택하고 request.json 옆에 스크립트를 저장하십시오. 그것은 FLASHDATA_API_KEY를 읽고, 또는 그것을 표시하지 않고 당신의 열쇠를 위해 신속한. 에이전트는 비밀 저장소에서 환경 변수를 공급해야 합니다.

출력 폴더로 검색-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를 유지하십시오. 이 파일을 읽기는 로컬; 빈 소스 배열은 유효한 outcome입니다.

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

### 예 출력

Illustrative 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/ko/docs/sources/google_search/reference.md)
- [Google Search 모범 사례](https://flashdata.dev/ko/docs/guides/google-search-guide/reference.md)

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

## 검색이 주의해야 하는 경우

| 어떤 일이 있었는지 | 해결 방법 |
| --- | --- |
| 401 / 403 / 402 | 키, google_search 권한 및 균형 확인, 각각. 이 시도를 계속하십시오; 당신이 다시 제출할 준비가 될 때만 새로운 출력 폴더를 사용하십시오. |
| 429 | response-headers.txt에서 Retry-After를 읽고 기다립니다. 스크립트는 자동으로 재부팅하지 않습니다. |
| Timeout, 5xx 또는 불완전 폴더 | 저장된 파일을 유지하고 다른 시도를 만들기 전에 History를 확인하십시오. 동일한 폴더를 다시 실행하면 새로운 요청이 없습니다. |
| 잘못된 JSON, 실패 상태 또는 예상치 못한 필드 | 소스를 추출하기 전에 result.json를 검사합니다. 잘못된 응답은 빈 성공적인 검색으로 처리되지 않아야합니다. |
| 유용한 소스 없음 | 저장된 쿼리를 검토합니다. 더 특정하거나 과도한 좁은 필터를 제거하고 다른 쿼리에 대한 새로운 폴더를 선택하십시오. |

### Python

저장 inspect_search.py 에서 웹 검색/ 전에 실행.

#### 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/ko/docs/errors/reference.md)
- [앱으로 검색하기](https://flashdata.dev/ko/docs/guides/search-in-an-app/reference.md)
