# 使用 Python 获取 Google 搜索结果并保存为 CSV

发送 Google Search API 请求，读取自然搜索结果，并使用 Python 标准库导出标题、URL 和摘要。

权威参考文档： https://flashdata.dev/zh/blog/google-search-python
博客: Google 搜索 · Python · FlashData
发布于: 2026-09-17
RSS: https://flashdata.dev/zh/blog/rss.xml

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

## 准备环境

您将使用 Python 3 及其标准库。创建一个 [API 密钥](https://flashdata.dev/app/api-keys) ，并确保账户有可用积分。如果这是你的第一次请求，请参阅 [API 快速入门](https://flashdata.dev/zh/docs/sources/google_search/reference.md#quickstart).

```bash
# Replace YOUR_API_KEY near the top of the code below.
```

下方脚本搜索 `openai` ，使用美国地区的结果和英文界面，然后将返回的自然搜索链接写入 CSV 文件。

<a id="request"></a>

## 获取并保存搜索结果

将脚本保存为 `search.py`。它提交一次实时请求，使用 `source: "google_search"` 并读取 `organic` 数组，该数组来自第一个结果。

```python
import csv
import json
import os
import urllib.request

base_url = "https://data.flashdata.dev"
api_key = "YOUR_API_KEY"
request = urllib.request.Request(
    base_url + "/v1/queries/realtime",
    data=json.dumps({
        "source": "google_search",
        "query": "openai",
        "params": {"gl": "us", "hl": "en", "num": 10},
    }).encode("utf-8"),
    headers={
        "X-API-Key": api_key,
        "Content-Type": "application/json",
    },
    method="POST",
)

with urllib.request.urlopen(request, timeout=60) as response:
    payload = json.load(response)

if payload.get("status") != "done":
    raise RuntimeError(payload.get("message", "Search did not complete"))

results = payload["results"][0].get("organic", [])
with open("google-results.csv", "w", newline="", encoding="utf-8") as output:
    writer = csv.DictWriter(output, fieldnames=["position", "title", "url", "snippet"])
    writer.writeheader()
    for result in results:
        writer.writerow({
            "position": result.get("position", ""),
            "title": result.get("title", ""),
            "url": result.get("link", ""),
            "snippet": result.get("snippet", ""),
        })

print(f"Saved {len(results)} results to google-results.csv")
```

```bash
python3 search.py
```

打开 `google-results.csv` ，可在电子表格中打开或加载到应用中。导出的列为 position、title、URL 和 snippet。Python 的 CSV 写入器会处理结果文本中逗号和换行符所需的引号。

<a id="response"></a>

## 理解 API 响应

这份记录的响应展示了搜索 OpenAI 时返回的数据结构。脚本会导出自然搜索结果中的链接；如果您的应用需要其他可用部分，它们仍保留在 API 响应中。

```json
{
  "source": "google_search",
  "status": "done",
  "results": [
    {
      "searchParameters": {
        "q": "openai",
        "gl": "us",
        "hl": "en",
        "type": "search",
        "num": 10,
        "page": 1,
        "engine": "google"
      },
      "organic": [
        {
          "title": "OpenAI | Research & Deployment",
          "link": "https://openai.com/",
          "snippet": "We believe our research will eventually lead to artificial general intelligence, a system that can solve human-level problems.",
          "position": 1
        },
        {
          "title": "OpenAI",
          "link": "https://en.wikipedia.org/wiki/OpenAI",
          "snippet": "OpenAI is an American artificial intelligence (AI) public benefit corporation (PBC) headquartered in San Francisco. It develops proprietary generative AI models ...",
          "position": 2
        },
        {
          "title": "OpenAI",
          "link": "https://x.com/OpenAI",
          "snippet": "OpenAI's mission is to ensure that artificial general intelligence benefits all of humanity. can develop research, build financial models, and create ...",
          "position": 3
        },
        {
          "title": "OpenAI",
          "link": "https://www.linkedin.com/company/openai",
          "snippet": "OpenAI is an AI research and deployment company dedicated to ensuring that general-purpose artificial intelligence benefits all of humanity.",
          "position": 4
        },
        {
          "title": "r/OpenAI",
          "link": "https://www.reddit.com/r/OpenAI/",
          "snippet": "OpenAI is an AI research and deployment company. OpenAI&#39;s mission is to create safe and powerful AI that benefits all of humanity. OpenAI's ...",
          "position": 5
        }
      ],
      "peopleAlsoAsk": [
        {
          "question": "Is OpenAI created by Elon Musk?"
        },
        {
          "question": "Why are people leaving ChatGPT?"
        },
        {
          "question": "Is OpenAI the same as ChatGPT?"
        },
        {
          "question": "Why is OpenAI in trouble?"
        }
      ],
      "relatedSearches": [
        {
          "query": "OpenAI login"
        },
        {
          "query": "OpenAI chat"
        },
        {
          "query": "OpenAI ChatGPT"
        },
        {
          "query": "OpenAI - wikipedia"
        },
        {
          "query": "OpenAI API"
        },
        {
          "query": "OpenAI app"
        },
        {
          "query": "OpenAI download"
        },
        {
          "query": "OpenAI video"
        }
      ]
    }
  ],
  "usage": {
    "credits": 0.02
  },
  "created_at": "2026-09-16T07:41:40.043Z"
}
```

该 `num` 参数用于请求结果数量，并不保证 Google 会返回相同数量的自然搜索链接。脚本会保存所有实际返回的结果。

<a id="next"></a>

## 更改搜索

更改 `query` 指定主题， `params.gl` 指定国家， `params.hl` 指定界面语言。使用 `params.page` ，请求下一页；每页都是单独的 API 调用。

如需比较不同时期的结果，请在每行数据中一并存储查询、区域和采集时间。API 返回的是搜索快照；历史比较依赖于您保存的快照。

## 相关指南

- [全部文章](https://flashdata.dev/zh/blog/reference.md)
- [测量 API 延迟与下载吞吐量](https://flashdata.dev/zh/docs/guides/performance/reference.md)
- [Google 搜索 API](https://flashdata.dev/zh/products/google-search/reference.md)
- [查看方案与费率](https://flashdata.dev/zh/pricing/google-search/reference.md)
- [服务商对比](https://flashdata.dev/zh/compare/reference.md)
- [Google Search API：在 Python 中设置国家/地区、语言和分页](https://flashdata.dev/zh/blog/google-search-country-language-pagination/reference.md)
- [2026 年 Google 搜索 JSON API 怎么选](https://flashdata.dev/zh/blog/google-search-json-api/reference.md)
