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

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

कैनोनिकल संदर्भ: https://flashdata.dev/hi/docs/guides/web-search-recipe
समीक्षित: 2026-11-05 द्वारा FlashData

<a id="prepare"></a>

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

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

- [API कुंजी लें](https://flashdata.dev/app/api-keys)
- [एजेंट परीक्षण का उपयोग](https://flashdata.dev/hi/docs/guides/agent-access/reference.md)
- [ऋण और मूल्य निर्धारण](https://flashdata.dev/hi/docs/guides/credits-and-billing/reference.md)

<a id="input"></a>

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

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

### web-search/request.json

```json
{
  "source": "google_search",
  "query": "battery recycling research",
  "params": {
    "num": 5
  }
}
```


<a id="run"></a>

## 2. सहेजें और स्क्रिप्ट चलाने

एक संस्करण चुनें और अपनी स्क्रिप्ट को request.json के बगल में सहेजें। यह FLASHDATA_API_KEY को पढ़ता है, या इसे प्रदर्शित किए बिना अपनी कुंजी के लिए प्रेरित करता है। एक एजेंट को अपने गुप्त स्टोर से पर्यावरण चर की आपूर्ति करनी चाहिए।

खोज-001 के साथ आउटपुट फ़ोल्डर के रूप में चलाएं। स्क्रिप्ट भेजने से पहले सटीक अनुरोध को बचाती है। एक ही फ़ोल्डर के साथ फिर से चल रहा है API को बुलाए बिना सहेजे गए प्रतिक्रिया को पढ़ता है।

### Python

#### अपने Python वातावरण में स्थापित करें

```bash
python -m pip install requests
```

#### web-search/search.py

```python
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")
```

#### वेब-खोज/वेब-खोज से भाग लें

```bash
python search.py search-001
```


### Bash

#### अपने उपकरण की जाँच करें

```bash
curl --version
jq --version
```

#### web-search/search.sh

```bash
#!/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
bash search.sh search-001
```



<a id="output"></a>

## 3. सहेजे गए स्रोतों को पढ़ें

सफलता प्रिंट ने एन सूत्रों को search-001/sources.json में सेव किया। सरणी Google के रिटर्न ऑर्डर में प्रत्येक सटीक लिंक की पहली घटना रहती है। एक उपयोगी लिंक के बिना पंक्तियाँ छोड़ी जाती हैं; लापता शीर्षक या स्निपेट मान null बने रहते हैं।

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

### Python

#### दोनों फाइलें पढ़ें

```bash
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.json
```


### Bash

#### दोनों फाइलें पढ़ें

```bash
cat search-001/sources.json
cat search-001/record.json
```



<a id="expected"></a>

### उदाहरण

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

#### web-search/search-001/sources.json

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


<a id="adapt"></a>

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

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

### web-search/request.json

```json
{
  "source": "google_search",
  "query": "site:energy.gov battery recycling research",
  "params": {
    "num": 5
  }
}
```

### Python

#### नई क्वेरी · एक अन्य बिलेबल अनुरोध

```bash
python search.py search-002
```


### Bash

#### नई क्वेरी · एक अन्य बिलेबल अनुरोध

```bash
bash search.sh search-002
```


- [खोज पैरामीटर](https://flashdata.dev/hi/docs/sources/google_search/reference.md)
- [Google Search सर्वोत्तम प्रथाओं](https://flashdata.dev/hi/docs/guides/google-search-guide/reference.md)

<a id="recover"></a>

## यदि खोज को ध्यान देने की जरूरत है

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

### Python

वेब-search में inspect_search.py सहेजें/ इसे चलाने से पहले।

#### web-search/inspect_search.py

```python
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")
```

#### स्थानीय रूप से निरीक्षण

```bash
python inspect_search.py
```


### Bash

#### स्थानीय रूप से निरीक्षण

```bash
for 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
```


- [अनुरोध इतिहास](https://flashdata.dev/app/jobs)
- [त्रुटियाँ और स्टेटस कोड](https://flashdata.dev/hi/docs/errors/reference.md)
- [एक एप्लिकेशन में खोज करें](https://flashdata.dev/hi/docs/guides/search-in-an-app/reference.md)
