本教程展示如何从 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 积分。重复查询会以半价自动从缓存提供。