본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

예제

웹 검색 및 소스 링크 저장

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

이 페이지의 내용

시작하기 전에

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

1. 자주 묻는 질문

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

web-search/request.json
{
  "source": "google_search",
  "query": "battery recycling research",
  "params": {
    "num": 5
  }
}

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

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

출력 폴더로 검색-001로 실행합니다. 스크립트는 보내기 전에 정확한 요청을 저장합니다. 동일한 폴더로 다시 실행하면 API를 호출하지 않고 저장된 응답을 읽습니다.

Python 환경에서 설치
python -m pip install requests
web-search/search.py
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")
웹 연구에서 실행 /
python search.py search-001

3. 저장된 소스를 읽으십시오

성공은 search-001/sources.json.에 N 소스를 저장 배열은 Google의 반환 순서에 있는 각 정확한 연결의 첫번째 발생을 지킵니다. 사용 가능한 링크가없는 행은 무효; 누락 된 제목 또는 스니펫 값은 null 남아있다.

record.json는 제출된 쿼리, 요청 시간 및 반환된 사용법을 포함합니다. 완전 응답으로 result.json를 유지하십시오. 이 파일을 읽기는 로컬; 빈 소스 배열은 유효한 outcome입니다.

두 파일을 읽으십시오
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.json

예 출력

Illustrative sources.json; 라이브 타이틀, 링크, 스니펫 및 카운트는 다를 수 있습니다. 답변에 대한 증거로 그들의 스니펫을 사용하기 전에 링크 된 페이지를 읽으십시오.

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

더 집중된 쿼리를 시도

도메인에 초점을 맞추려면 아래 예로 request.json에서 쿼리를 변경하십시오. 새로운 쿼리에 대한 새로운 출력 폴더를 선택하십시오. Search-001는 항상 원래 저장된 요청을 나타냅니다.

web-search/request.json
{
  "source": "google_search",
  "query": "site:energy.gov battery recycling research",
  "params": {
    "num": 5
  }
}
새로운 질문 · 다른 청구서블 요청
python search.py search-002

검색이 주의해야 하는 경우

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

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

web-search/inspect_search.py
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")
로컬로 검사
python inspect_search.py