← 返回博客

Python 中的 Google 搜索 API:完整教程(2026)

如何在 Python 中使用 Google 搜索 API——身份验证请求、解析结果、分页、重试以及一个可复用的客户端类,附带示例。

1 分钟阅读

本教程展示如何从 Python 查询 Google 并获得干净、结构化的结果——使用 serp.cheap,这是 2026 年最便宜的 Google 搜索 API。

安装

pip install requests

最简示例

import requests

resp = requests.post(
    "https://api.serp.cheap/v1/search",
    headers={"X-API-Key": "YOUR_KEY"},
    json={"q": "best electric cars 2026", "gl": "us", "page": 1},
    timeout=30,
)
resp.raise_for_status()
for r in resp.json()["organic"]:
    print(f'#{r["position"]} {r["title"]} — {r["link"]}')

带重试的可复用客户端

import requests
from requests.adapters import HTTPAdapter, Retry

class SerpClient:
    def __init__(self, api_key: str):
        self.s = requests.Session()
        self.s.headers.update({"X-API-Key": api_key})
        retries = Retry(total=4, backoff_factor=1.5,
                        status_forcelist=[429, 500, 502, 503, 504])
        self.s.mount("https://", HTTPAdapter(max_retries=retries))

    def search(self, q, gl="us", page=1, tbs=None):
        body = {"q": q, "gl": gl, "page": page}
        if tbs:
            body["tbs"] = tbs
        r = self.s.post("https://api.serp.cheap/v1/search", json=body, timeout=30)
        r.raise_for_status()
        return r.json()

client = SerpClient("YOUR_KEY")
data = client.search("python web scraping", gl="us")
print(data["stats"])  # balance, cost, cached

分页

def all_results(client, q, pages=3, gl="us"):
    out = []
    for p in range(1, pages + 1):
        out += client.search(q, gl=gl, page=p)["organic"]
    return out

每一页都是单独计费的请求——请按需懒加载获取。更多内容见 分页。

成本控制

stats.cost 以积分为单位(1 = $0.0001)。缓存命中花费 3 积分,全新抓取花费 6 积分。重复查询会以半价自动从缓存提供。

下一步

Frequently asked questions

在 Python 中调用 Google 搜索 API 最简单的方式是什么?+

使用 requests 库将你的查询 POST 到 SERP API。使用 serp.cheap:requests.post('https://api.serp.cheap/v1/search', headers={'X-API-Key': KEY}, json={'q': query, 'gl': 'us'})。响应 JSON 中包含一个 organic[] 列表。更喜欢类型化的客户端?用 pip install serpcheap 安装官方 SDK(同时也提供 Django 和 FastAPI 集成)。

在 Python 中如何处理速率限制?+

捕获 HTTP 429 并使用指数退避进行重试(例如通过 urllib3 Retry 或 tenacity)。每分钟 60 次请求(1 次/秒)只是 serp.cheap 免费层的限制;按量付费(PAYG)为每分钟 600 次请求(10 次/秒),顶级套餐最高可达 60 次/秒。

获取你的 API 密钥

直接购买最便宜, 用银行卡或加密货币支付,无需 KYC。或通过市场。