# Cercare il web e salvare i link sorgente

Eseguire una ricerca Google. Salvare link di origine unici in ordine di risultato, insieme alla query e l'utilizzo.

Riferimento canonico: https://flashdata.dev/it/docs/guides/web-search-recipe
Recensito: 2026-11-05 da FlashData

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

## Prima di iniziare

Utilizzare una chiave con il permesso google_search e i crediti disponibili. Scegliere Python 3.10+ con richieste, o Bash con cURL 7.76+ e jq. Su Windows, utilizzare Git Bash per il percorso Bash.

- [Ottieni una chiave API](https://flashdata.dev/app/api-keys)
- [Accesso alla prova dell'agente](https://flashdata.dev/it/docs/guides/agent-access/reference.md)
- [Crediti e prezzi](https://flashdata.dev/it/docs/guides/credits-and-billing/reference.md)

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

## 1. Preparare la query

Creare una cartella di ricerca web. Salvare request.json lì, quindi aprire un terminale in quella cartella. Questo esempio richiede fino a cinque risultati organici; un nuovo run presenta una domanda fatturabile.

### web-search/request.json

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


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

## 2. Salvare ed eseguire lo script

Scegliere una versione e salvare il suo script accanto a request.json. Legge FLASHDATA_API_KEY, o richieste per la chiave senza visualizzarla. Un agente dovrebbe fornire la variabile di ambiente dal suo negozio segreto.

Eseguire con ricerca-001 come cartella di uscita. Lo script salva la richiesta esatta prima di inviarlo. Correre di nuovo con la stessa cartella legge la risposta salvata senza chiamare API.

### Python

#### Installare nel tuo ambiente 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")
```

#### Esegui dal web-search/

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


### Bash

#### Controlla i tuoi strumenti

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

#### Esegui dal web-search/

```bash
bash search.sh search-001
```



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

## 3. Leggi le fonti salvate

Stampe di successo Salvate N fonti a search-001/sources.json. L'array mantiene la prima occorrenza di ogni link esatto nell'ordine restituito di Google. Le righe senza un collegamento utilizzabile sono omesse; il titolo mancante o i valori di snippet rimangono null.

record.json contiene la query presentata, il tempo di richiesta e l'utilizzo restituito. Mantenere result.json come risposta completa. La lettura di questi file è locale; un array di fonti vuote è un risultato valido.

### Python

#### Leggi entrambi i file

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


### Bash

#### Leggi entrambi i file

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



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

### Esempio di output

Illustrativo sources.json; titoli dal vivo, link, frammenti e conteggi variano. Leggere le pagine collegate prima di utilizzare i loro frammenti come prova per una risposta.

#### 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>

## Prova una query più focalizzata

Per concentrarsi su un dominio, cambiare la query in request.json all'esempio qui sotto. Scegliere una nuova cartella di output per la nuova query; ricerca-001 si riferisce sempre alla sua richiesta salvata originale.

### web-search/request.json

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

### Python

#### Nuova domanda · un'altra richiesta fatturabile

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


### Bash

#### Nuova domanda · un'altra richiesta fatturabile

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


- [Parametri di ricerca](https://flashdata.dev/it/docs/sources/google_search/reference.md)
- [Google Cerca le migliori pratiche](https://flashdata.dev/it/docs/guides/google-search-guide/reference.md)

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

## Se la ricerca ha bisogno di attenzione

| Che cosa è successo? | Cosa fare |
| --- | --- |
| 401 / 403 / 402 | Controllare la chiave, google_search permesso e equilibrio, rispettivamente. Tenere questo tentativo; utilizzare una nuova cartella di output solo quando si è pronti a presentare di nuovo. |
| 429 | Leggi Retry-After in response-headers.txt e aspetta. Gli script non si riprendono automaticamente. |
| Timeout, 5xx o una cartella incompleta | Tenere i file salvati e controllare History prima di creare un altro tentativo. Reinviare la stessa cartella non fa alcuna nuova richiesta. |
| Invalid JSON, stato fallito o campi inaspettati | Ispezionare result.json prima di estrarre le fonti. Una risposta non valida non deve essere trattata come una ricerca di successo vuota. |
| Nessuna fonte utile | Rivedere la query salvata. Renderlo più specifico o rimuovere un filtro eccessivamente stretto, quindi scegliere una nuova cartella per un'altra query. |

### Python

Salvare inspect_search.py in web-search/ prima di eseguirlo.

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

#### Ispezione locale

```bash
python inspect_search.py
```


### Bash

#### Ispezione locale

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


- [Richiedi la cronologia](https://flashdata.dev/app/jobs)
- [Errori e codici di stato](https://flashdata.dev/it/docs/errors/reference.md)
- [Costruire la ricerca in un'applicazione](https://flashdata.dev/it/docs/guides/search-in-an-app/reference.md)
