दस्तावेज़ देखें
उदाहरण
एक Google खोज को चलाएं। परिणाम क्रम में अद्वितीय स्रोत लिंक सहेजें, साथ ही साथ क्वेरी और उपयोग के साथ।
इस पेज पर
शुरू करने से पहले
google_search अनुमति और उपलब्ध क्रेडिट के साथ एक कुंजी का उपयोग करें। Python 3.10+ को अनुरोधों के साथ चुनें, या Bash को cURL 7.76+ और jq के साथ चुनें। Windows पर, Git Bash का उपयोग Bash पथ के लिए किया जाता है।
1. क्वेरी तैयार करना
एक वेब-खोज फ़ोल्डर बनाएँ। वहाँ request.json सहेजें, फिर उस फ़ोल्डर में एक टर्मिनल खोलें। यह उदाहरण पांच कार्बनिक परिणामों के लिए अनुरोध करता है; एक नया रन एक बिलेबल क्वेरी प्रस्तुत करता है।
{
"source": "google_search",
"query": "battery recycling research",
"params": {
"num": 5
}
}2. सहेजें और स्क्रिप्ट चलाने
एक संस्करण चुनें और अपनी स्क्रिप्ट को request.json के बगल में सहेजें। यह FLASHDATA_API_KEY को पढ़ता है, या इसे प्रदर्शित किए बिना अपनी कुंजी के लिए प्रेरित करता है। एक एजेंट को अपने गुप्त स्टोर से पर्यावरण चर की आपूर्ति करनी चाहिए।
खोज-001 के साथ आउटपुट फ़ोल्डर के रूप में चलाएं। स्क्रिप्ट भेजने से पहले सटीक अनुरोध को बचाती है। एक ही फ़ोल्डर के साथ फिर से चल रहा है 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. सहेजे गए स्रोतों को पढ़ें
सफलता प्रिंट ने एन सूत्रों को search-001/sources.json में सेव किया। सरणी Google के रिटर्न ऑर्डर में प्रत्येक सटीक लिंक की पहली घटना रहती है। एक उपयोगी लिंक के बिना पंक्तियाँ छोड़ी जाती हैं; लापता शीर्षक या स्निपेट मान null बने रहते हैं।
record.json में प्रस्तुत क्वेरी, अनुरोध समय और वापस उपयोग शामिल है। पूर्ण प्रतिक्रिया के रूप में result.json को रखें। इन फ़ाइलों को पढ़ना स्थानीय है; एक खाली स्रोत सरणी एक वैध परिणाम है।
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.jsoncat search-001/sources.json
cat search-001/record.jsonउदाहरण
illustrated sources.json; लाइव शीर्षक, लिंक, स्निपेट्स और गिनती भिन्न होती है। अपने स्निपेट्स का उपयोग करने से पहले उनके snippets को उत्तर देने के लिए सबूत के रूप में पढ़ें।
[
{
"title": "Battery recycling research",
"link": "https://example.org/recycling",
"snippet": "An example search excerpt."
}
]अधिक ध्यान केंद्रित क्वेरी आज़माएं
एक डोमेन पर ध्यान केंद्रित करने के लिए, नीचे दिए गए उदाहरण के लिए request.json में क्वेरी बदलें। नए क्वेरी के लिए एक नया आउटपुट फ़ोल्डर चुनें; सर्च-001 हमेशा अपने मूल सहेजे गए अनुरोध को संदर्भित करता है।
{
"source": "google_search",
"query": "site:energy.gov battery recycling research",
"params": {
"num": 5
}
}python search.py search-002bash search.sh search-002यदि खोज को ध्यान देने की जरूरत है
| क्या हुआ | क्या करें |
|---|---|
| 401 / 403 / 402 | क्रमश: कुंजी, google_search अनुमति और शेष की जाँच करें। इस प्रयास को बनाए रखें; जब आप फिर से जमा करने के लिए तैयार हों तो केवल एक नए आउटपुट फ़ोल्डर का उपयोग करें। |
| 429 | Retry-After को response-headers.txt में पढ़ें और प्रतीक्षा करें। स्क्रिप्ट स्वचालित रूप से फिर से नहीं आती है। |
| टाइमआउट, 5xx या एक अधूरा फ़ोल्डर | सहेजी गई फ़ाइलों को रखने और एक और प्रयास बनाने से पहले History की जाँच करें। एक ही फ़ोल्डर को चलाने से कोई नया अनुरोध नहीं होता है। |
| Invalid JSON, असफल स्थिति या अप्रत्याशित क्षेत्र | सूत्रों को निकालने से पहले result.json का निरीक्षण करें। एक अमान्य प्रतिक्रिया को खाली सफल खोज के रूप में नहीं माना जाना चाहिए। |
| कोई उपयोगी स्रोत नहीं | सहेजे गए क्वेरी की समीक्षा करें। इसे अधिक विशिष्ट बनाएं या ओवरली संकीर्ण फ़िल्टर को हटा दें, फिर किसी अन्य क्वेरी के लिए एक नया फ़ोल्डर चुनें। |
वेब-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.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