सीधे सामग्री पर जाएँ
HI
API कुंजी प्राप्त करें
दस्तावेज़ देखें

उदाहरण

वेब खोजें और स्रोत लिंक सहेजें

एक Google खोज को चलाएं। परिणाम क्रम में अद्वितीय स्रोत लिंक सहेजें, साथ ही साथ क्वेरी और उपयोग के साथ।

इस पेज पर

शुरू करने से पहले

google_search अनुमति और उपलब्ध क्रेडिट के साथ एक कुंजी का उपयोग करें। Python 3.10+ को अनुरोधों के साथ चुनें, या Bash को cURL 7.76+ और jq के साथ चुनें। Windows पर, Git Bash का उपयोग Bash पथ के लिए किया जाता है।

1. क्वेरी तैयार करना

एक वेब-खोज फ़ोल्डर बनाएँ। वहाँ request.json सहेजें, फिर उस फ़ोल्डर में एक टर्मिनल खोलें। यह उदाहरण पांच कार्बनिक परिणामों के लिए अनुरोध करता है; एक नया रन एक बिलेबल क्वेरी प्रस्तुत करता है।

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 में सेव किया। सरणी Google के रिटर्न ऑर्डर में प्रत्येक सटीक लिंक की पहली घटना रहती है। एक उपयोगी लिंक के बिना पंक्तियाँ छोड़ी जाती हैं; लापता शीर्षक या स्निपेट मान null बने रहते हैं।

record.json में प्रस्तुत क्वेरी, अनुरोध समय और वापस उपयोग शामिल है। पूर्ण प्रतिक्रिया के रूप में result.json को रखें। इन फ़ाइलों को पढ़ना स्थानीय है; एक खाली स्रोत सरणी एक वैध परिणाम है।

दोनों फाइलें पढ़ें
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.json

उदाहरण

illustrated sources.json; लाइव शीर्षक, लिंक, स्निपेट्स और गिनती भिन्न होती है। अपने स्निपेट्स का उपयोग करने से पहले उनके snippets को उत्तर देने के लिए सबूत के रूप में पढ़ें।

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

अधिक ध्यान केंद्रित क्वेरी आज़माएं

एक डोमेन पर ध्यान केंद्रित करने के लिए, नीचे दिए गए उदाहरण के लिए request.json में क्वेरी बदलें। नए क्वेरी के लिए एक नया आउटपुट फ़ोल्डर चुनें; सर्च-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 अनुमति और शेष की जाँच करें। इस प्रयास को बनाए रखें; जब आप फिर से जमा करने के लिए तैयार हों तो केवल एक नए आउटपुट फ़ोल्डर का उपयोग करें।
429Retry-After को response-headers.txt में पढ़ें और प्रतीक्षा करें। स्क्रिप्ट स्वचालित रूप से फिर से नहीं आती है।
टाइमआउट, 5xx या एक अधूरा फ़ोल्डरसहेजी गई फ़ाइलों को रखने और एक और प्रयास बनाने से पहले History की जाँच करें। एक ही फ़ोल्डर को चलाने से कोई नया अनुरोध नहीं होता है।
Invalid JSON, असफल स्थिति या अप्रत्याशित क्षेत्रसूत्रों को निकालने से पहले result.json का निरीक्षण करें। एक अमान्य प्रतिक्रिया को खाली सफल खोज के रूप में नहीं माना जाना चाहिए।
कोई उपयोगी स्रोत नहींसहेजे गए क्वेरी की समीक्षा करें। इसे अधिक विशिष्ट बनाएं या ओवरली संकीर्ण फ़िल्टर को हटा दें, फिर किसी अन्य क्वेरी के लिए एक नया फ़ोल्डर चुनें।

वेब-search में 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
Markdown