跳转到正文
中文
获取 API 密钥
浏览文档

示例

搜索网页并保存来源链接

运行一次 Google 搜索,按结果顺序保存不重复的来源链接,以及查询和用量。

本页内容

开始前准备

需要具有 google_search 权限的密钥和可用额度。选择 Python 3.10+ 与 requests,或 Bash、cURL 7.76+ 与 jq。Windows 的 Bash 路径请使用 Git Bash。

1. 准备查询

创建 web-search 文件夹,将 request.json 保存到其中,并在该文件夹打开终端。本例请求最多五条自然搜索结果;每次新运行提交一次计费查询。

web-search/request.json
{
  "source": "google_search",
  "query": "battery recycling research",
  "params": {
    "num": 5
  }
}

2. 保存并运行脚本

选择一种版本,将脚本保存到 request.json 旁。它读取 FLASHDATA_API_KEY,或通过隐藏输入提示获取密钥。智能体应从密钥存储提供该环境变量。

将 search-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")
在 web-search/ 中运行
python search.py search-001

3. 读取已保存的来源

成功后输出 Saved N sources to search-001/sources.json。数组按 Google 返回顺序保留每个完全相同链接的首次出现。不含有效链接的行会被忽略;缺失的 title 或 snippet 保留为 null。

record.json 包含实际提交的查询、请求时间和返回用量。result.json 保留完整响应。读取这些文件只在本地进行;来源数组为空也是有效结果。

读取两个文件
python -m json.tool search-001/sources.json
python -m json.tool search-001/record.json

输出示例

下方为 sources.json 示意,实际标题、链接、摘要和数量会变化。将摘要作为回答依据前,先阅读链接中的页面。

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

尝试更具体的查询

聚焦某个域名时,将 request.json 中的 query 改为下例。新查询需使用新的输出文件夹;search-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 权限及余额。保留本次尝试,准备重新提交时才使用新输出文件夹。
429读取 response-headers.txt 中的 Retry-After 并等待。脚本不会自动重试。
超时、5xx 或文件夹内容不完整保留已有文件,创建新尝试前检查请求历史。同一文件夹再次运行不会发起新请求。
JSON 无效、状态失败或字段异常提取来源前检查 result.json。不能将无效响应当作成功的空搜索结果。
无可用来源检查保存的查询,增加具体信息或移除过窄筛选,再为新查询选择新的文件夹。

先将 inspect_search.py 保存到 web-search/,再运行。

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