Przeglądaj dokumentację
Przykłady
Uruchom jedno wyszukiwanie Google. Zapisz unikalne łącza źródłowe w kolejności wyników, wraz z zapytaniem i użyciem.
Na tej stronie
Zanim zaczniesz
Użyj klucza z pozwoleniem google_search i dostępnymi kredytami. Wybierz Python 3.10 + z życzeniami lub Bash z cURL 7.76 + i jq. Na Windows użyj Git Bash do ścieżki Bash.
1. Przygotuj zapytanie
Utwórz folder web- search. Zapisz tam request.json, a następnie otwórz terminal w tym folderze. Ten przykład wymaga do pięciu wyników ekologicznych; jeden nowy ciąg zawiera jedno billingible query.
{
"source": "google_search",
"query": "battery recycling research",
"params": {
"num": 5
}
}2. Zapisz i uruchom skrypt
Wybierz jedną wersję i zapisz jej skrypt obok request.json. Czyta FLASHDATA_API_KEY, lub podsuwa klucz bez wyświetlania go. Agent powinien dostarczyć zmienną środowiskową ze swojego tajnego sklepu.
Uruchom z wyszukiwarką 001 jako folder wyjściowy. Skrypt zapisuje dokładne żądanie przed wysłaniem go. Uruchomienie ponownie z tym samym folderem odczytuje zapisaną odpowiedź bez wywołania API.
python -m pip install requestsimport 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-001curl --version
jq --version#!/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 search.sh search-0013. Przeczytaj zapisane źródła
Odciski sukcesu Zapisane źródła N do search-001/sources.json. Karta zachowuje pierwsze wystąpienie każdego dokładnego odnośnika w zwrotnym porządku Google. Wiersze bez użytecznego łącza są pomijane; brakujące wartości tytułu lub skrótu pozostają null.
record.json zawiera złożone zapytanie, czas żądania i zwrócone użycie. Należy zachować result.json jako pełną odpowiedź. Czytanie tych plików jest lokalne; pusta tablica źródłowa jest prawidłowym wynikiem.
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.jsoncat search-001/sources.json
cat search-001/record.jsonPrzykład wyjścia
Ilustracyjne sources.json; tytuły na żywo, linki, wycinanki i liczniki różnią się. Przeczytaj powiązane strony przed użyciem ich snippets jako dowód odpowiedzi.
[
{
"title": "Battery recycling research",
"link": "https://example.org/recycling",
"snippet": "An example search excerpt."
}
]Spróbuj bardziej skoncentrowane zapytanie
Aby skupić się na domenie, zmień zapytanie w request.json na poniższy przykład. Wybierz nowy folder wyjściowy dla nowego zapytania; search- 001 zawsze odnosi się do oryginalnego zapisanego żądania.
{
"source": "google_search",
"query": "site:energy.gov battery recycling research",
"params": {
"num": 5
}
}python search.py search-002bash search.sh search-002Jeśli wyszukiwanie wymaga uwagi
| Co się stało? | Co zrobić |
|---|---|
| 401 / 403 / 402 | Sprawdź klucz, odpowiednio pozwolenie google_search i saldo. Zachowaj tę próbę; użyj nowego folderu wyjściowego tylko wtedy, gdy jesteś gotowy do złożenia ponownie. |
| 429 | Przeczytaj Retry-After w response-headers.txt i czekaj. Skrypty nie sprawdzają się automatycznie. |
| Czas, 5xx lub niekompletny folder | Zachowaj zapisane pliki i sprawdź History przed utworzeniem kolejnej próby. Przekierowanie tego samego folderu nie powoduje żadnych nowych wymagań. |
| Nieprawidłowy status JSON, nieudany status lub nieoczekiwane pola | Sprawdź result.json przed wydobyciem źródeł. Nieprawidłowa odpowiedź nie może być traktowana jako puste pomyślne wyszukiwanie. |
| Brak użytecznych źródeł | Przejrzyj zapisane zapytanie. Zrób to bardziej szczegółowo lub usunąć zbyt wąski filtr, a następnie wybierz nowy folder dla innego zapytania. |
Zapisz inspect_search.py w web- search / przed uruchomieniem.
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.pyfor 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