# ค้นหาเว็บและบันทึกลิงก์แหล่งข้อมูล

ค้นหา Google หนึ่งครั้ง บันทึกลิงก์แหล่งข้อมูลที่ไม่ซ้ำตามลำดับผลลัพธ์ พร้อมคำค้นและข้อมูลการใช้งาน

อ้างอิงทางคลอง: https://flashdata.dev/th/docs/guides/web-search-recipe
Recorder: 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/th/docs/guides/agent-access/reference.md)
- [เงิน เครดิต และ ราคา](https://flashdata.dev/th/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 สภาพแวดล้อมName

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

#### ประมวลผลจาก web-search/

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


### Bash

#### Check เครื่องของคุณ

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

#### ประมวลผลจาก web-search/

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



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

## 3. อ่านแหล่งที่บันทึกไว้

ลายนิ้วมือที่ประสบความสําเร็จได้บันทึกแหล่งข้อมูล N ไปยัง search-001/sources.json. อาร์เรย์เก็บการเกิดขึ้นครั้งแรกของแต่ละลิงก์ที่แน่นอนใน Googleคําสั่งกลับแล้ว แถวที่ขาดลิงก์ที่สามารถใช้ได้ จะไม่มีตําแหน่งหรือค่าตัวแยก null.

record.json บรรจุคําร้องขอ, ร้องขอเวลา และคืนการใช้งาน เก็บไว้ result.json ทั้งนี้เป็นการตอบแทนอย่างคู่ควร การอ่านแฟ้มเหล่านี้เป็นภายในเครื่องของคุณ; รายการต้นทางที่ว่างเปล่าจะเป็นผลลัพธ์ที่ถูกต้อง

### Python

#### อ่านทั้ง 2 แฟ้ม

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


### Bash

#### อ่านทั้ง 2 แฟ้ม

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



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

### ตัวอย่างผลลัพธ์

ตัวอย่าง sources.json เพื่ออธิบายรูปแบบ ชื่อเรื่อง ลิงก์ ข้อความสรุป และจำนวนผลลัพธ์จริงอาจต่างกัน อ่านหน้าเว็บที่ลิงก์ไปก่อนใช้ข้อความสรุปเป็นหลักฐานในคำตอบ

#### 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/th/docs/sources/google_search/reference.md)
- [แนวทางใช้ Google Search](https://flashdata.dev/th/docs/guides/google-search-guide/reference.md)

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

## ถ้าการค้นหาต้องการความสนใจ

| เกิดอะไรขึ้น | วิธีแก้ไข |
| --- | --- |
| 401 / 403 / 402 | ตรวจสอบกุญแจ google_search อนุญาตให้ใช้งานและสมดุลย์ตามลําดับ คงการลองนี้ไว้ ใช้โฟลเดอร์ส่งออกเสียงตัวใหม่เฉพาะเมื่อ คุณพร้อมที่จะส่งข้อมูลอีกครั้ง |
| 429 | อ่าน Retry-After ใน response-headers.txt และรอ. ไม่ให้ลองใหม่โดยอัตโนมัติ |
| หมดเวลา, 5xx หรือโฟลเดอร์ที่ยังไม่สมบูรณ์ | เก็บแฟ้มที่บันทึกไว้และตรวจสอบ History ก่อนจะสร้างความพยายามอีกครั้ง การเรียกโฟลเดอร์เดิมใหม่ ไม่เป็นการขอใหม่ |
| ไม่ถูกต้อง JSON_สถานะหรือรายการที่ไม่คาดคิด | Inspect result.json ก่อนทําการสกัดแหล่งข้อมูล การตอบสนองไม่ถูกต้อง ต้องไม่มีผลเป็นการค้นหาที่ล้มเหลว |
| ไม่มีแหล่งที่มีประโยชน์ | ทบทวนการสอบถามที่บันทึกไว้ ให้มันระบุหรือลบตัวกรองที่แคบเกินไป แล้วเลือกโฟลเดอร์ใหม่สําหรับการสอบถามอื่น ๆ |

### Python

บันทึก 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/th/docs/errors/reference.md)
- [สร้างการค้นหาไปยังโปรแกรม](https://flashdata.dev/th/docs/guides/search-in-an-app/reference.md)
