# Tìm kiếm web và lưu liên kết nguồn

Tìm kiếm Google. Lưu liên kết độc đáo trong thứ tự kết quả, cùng với yêu cầu và sử dụng.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/guides/web-search-recipe
Xem lại: 2026-11-05 by FlashData

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

## Trước khi bắt đầu

Dùng phím google_search Cho phép và tín dụng sẵn có. Chọn Python 3.10+ với yêu cầu, hoặc Bash có cURL 7.76+ và jq. Vào Windowssử dụng Git Bash cho Bash con đường.

- [Lấy khóa API](https://flashdata.dev/app/api-keys)
- [Truy cập thử tác nhân](https://flashdata.dev/vi/docs/guides/agent-access/reference.md)
- [Tín dụng và giá cả](https://flashdata.dev/vi/docs/guides/credits-and-billing/reference.md)

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

## 1. Chuẩn bị truy vấn

Tạo thư mục tìm kiếm web. Lưu request.json thì mở một thiết bị cuối trong thư mục đó. Ví dụ này yêu cầu 5 kết quả hữu cơ; một chạy bộ mới đệ trình một yêu cầu có thể tính toán.

### web-search/request.json

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


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

## 2. Lưu và chạy văn lệnh

Chọn một phiên bản và lưu văn lệnh bên cạnh request.json. Nó đọc FLASHDATA_API_KEYhoặc gợi ý cho chìa khóa của bạn mà không cần hiển thị nó. Một tác nhân nên cung cấp biến môi trường từ cửa hàng bí mật của nó.

Chạy với tìm kiếm-001 là thư mục xuất. Văn lệnh lưu chính xác yêu cầu trước khi gửi nó. Chạy lại với cùng một thư mục đọc câu trả lời đã lưu mà không gọi API.

### Python

#### Cài đặt trong môi trường Python của bạn

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

#### Chạy từ tìm kiếm web/

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


### Bash

#### Kiểm tra dụng cụ của bạn

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

#### Chạy từ tìm kiếm web/

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



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

## 3. Đọc các nguồn đã lưu

Thành công in N nguồn tới search-001/sources.json. Bảng giữ lần đầu tiên gặp mỗi liên kết chính xác trong GoogleMệnh lệnh đã được trả lại. Hàng không có liên kết có khả năng sử dụng bị bỏ qua; còn thiếu tiêu đề hay giá trị trích đoạn còn lại null.

record.json chứa các yêu cầu đã gửi, yêu cầu thời gian và sử dụng lại. Giữ result.json làm phản hồi đầy đủ. Đọc những tập tin này là cục bộ; một danh sách nguồn rỗng là một kết quả hợp lệ.

### Python

#### Đọc cả hai tập tin

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


### Bash

#### Đọc cả hai tập tin

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



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

### Đầu ra Ví dụ

Ảo tưởng sources.json; tiêu đề sống, liên kết, trích đoạn và số khác nhau. Hãy đọc những trang liên kết trước khi dùng những đoạn trích của chúng làm bằng chứng cho câu trả lời.

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

## Thử truy vấn tiêu điểm hơn

Để tập trung vào một miền, thay đổi truy vấn trong request.json để ví dụ dưới đây. Chọn một thư mục xuất mới cho yêu cầu mới; tìm kiếm001 luôn luôn đề cập đến yêu cầu cứu rỗi nguyên thủy của nó.

### web-search/request.json

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

### Python

#### Comment

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


### Bash

#### Comment

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


- [Tham số tìm kiếm](https://flashdata.dev/vi/docs/sources/google_search/reference.md)
- [Google Search Thực hành tốt nhất](https://flashdata.dev/vi/docs/guides/google-search-guide/reference.md)

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

## Nếu tìm kiếm cần sự chú ý

| Chuyện gì đã xảy ra | Cách xử lý |
| --- | --- |
| 401 / 403 / 402 | Kiểm tra chìa khóa đi. google_search cho phép và số dư, anh bạn. Hãy giữ điều này cố gắng; chỉ sử dụng một thư mục xuất mới khi bạn sẵn sàng để gởi lại. |
| 429 | Đọc Retry-After in response-headers.txt và chờ đợi. Tập lệnh không tự động thử lại. |
| Thời hạn, 5x hoặc một thư mục không đầy đủ | Giữ các tập tin đã lưu và kiểm tra History Trước khi tạo ra một nỗ lực khác. Chạy lại cùng một thư mục không có yêu cầu mới. |
| JSON không hợp lệ, trạng thái thất bại hoặc trường bất ngờ | Kiểm tra result.json Trước khi khai thác nguồn. Không thể đối phó một đáp ứng không hợp lệ như một tìm kiếm thành công rỗng. |
| Không có nguồn hữu ích | Hãy xem lại câu hỏi đã lưu. Hãy làm cho nó cụ thể hơn hoặc gỡ bỏ một bộ lọc quá hẹp, sau đó chọn một thư mục mới cho một yêu cầu khác. |

### Python

Lưu inspect_search.py trong việc tìm kiếm web/ trước khi chạy nó.

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

#### Kiểm tra cục bộ

```bash
python inspect_search.py
```


### Bash

#### Kiểm tra cục bộ

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


- [Yêu cầu lịch sử](https://flashdata.dev/app/jobs)
- [Lỗi và mã trạng thái](https://flashdata.dev/vi/docs/errors/reference.md)
- [Xây dựng tìm kiếm vào ứng dụng](https://flashdata.dev/vi/docs/guides/search-in-an-app/reference.md)
