浏览文档
示例
运行一次 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 requestsweb-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检查工具
curl --version
jq --versionweb-search/search.sh
#!/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 search.sh search-0013. 读取已保存的来源
成功后输出 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读取两个文件
cat search-001/sources.json
cat 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新查询 · 另一次计费请求
bash search.sh 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本地检查
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