تصفح الوثائق
أمثلة
اركضي Google البحث. Provide unique source links in result order, together with the query and usage.
في هذه الصفحة
قبل أن تبدأ
استخدم مفتاحًا بصلاحية google_search ورصيد متاح. اختر Python 3.10+ مع requests أو 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الناتج المثالي
ملف sources.json توضيحي؛ وتختلف العناوين والروابط والمقتطفات والأعداد الفعلية. اقرأ الصفحات المرتبطة قبل استخدام مقتطفاتها كأدلة للإجابة.
[
{
"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 وانتظر. النصوص لا تعود تلقائياً |
| وقت مستقطع، 5x أو ملف غير كامل | احتفظ بالملفات المحتفظ بها وتحقق History قبل أن نخلق محاولة أخرى إعادة إدارة نفس الملف لا تقدم أي طلب جديد |
| Invalid JSON, failed status or expected fields | Inspect result.json before extracting sources. ويجب ألا يُعامل الرد غير الصحيح على أنه بحث ناجح فارغ. |
| لا توجد مصادر مفيدة | افحصوا الإستفسار اجعله أكثر تحديداً أو أزيل مرشح ضيق جداً ثم أختار ملفاً جديداً لسؤال آخر |
احفظ inspect_search.py داخل web-search/ قبل تشغيله.
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