在竞品分析、SEO 排名监控、品牌舆情追踪以及 AI 检索数据集采集中,使用 Python 抓取 Google 搜索结果(SERP)是最普遍的技术需求之一。然而,任何曾尝试使用 BeautifulSoup、Selenium 或 Playwright 从零自建爬虫的开发者很快都会发现:在生产规模下长期维护自建爬虫是一项巨大的运维负担。
Google 会严密审查 TLS 握手特征(JA3/JA4 指纹)、浏览器 Canvas 哈希、IP 信誉以及高频请求节奏。在没有完善住宅代理池的情况下直接运行原生 Python 脚本,短时间内就会遭遇 HTTP 429 Too Many Requests 或弹出交互式 reCAPTCHA 阻断。
本指南将演示如何借助 Python 配合 Serqo 工业级 SERP API,在 2 秒内稳定获取去冗余的结构化 JSON 搜索结果。
自建 Python 爬虫与商业 SERP API 核心对比
| 痛点维度 | 自建本地爬虫(BS4 / Playwright) | 托管式 SERP API(Serqo) |
|---|---|---|
| IP 封禁与验证码 | 需自行采购、调度并维护昂贵的住宅代理池,耗时费力。 | 云端内置全球住宅 IP 自动轮换,全自动绕过验证码。 |
| 页面改版失效风险 | Google 频繁混淆 DOM 节点与类名,爬虫解析规则极易破损。 | 承诺强类型的标准化 JSON 输出(title, url, snippet, position)。 |
| 服务器资源与延迟 | 无头浏览器单实例占用 500MB+ 内存,单页抓取长达 4–8 秒。 | 轻量异步 HTTP 传输,1.2 至 2.5 秒极速返回。 |
| 综合投入产出比 | 未写业务逻辑前,每月代理带宽与服务器成本已达数百美元。 | 套餐低至 /月(千次 .50),未用额度永久结转不过期。 |
第一步:安装依赖库
仅需 Python 3.9+ 环境和现代 HTTP 客户端库(如 httpx 或 requests),无需任何无头浏览器驱动或复杂的自动化依赖:
pip install httpx
第二步:5 行 Python 代码发起 Google 搜索
在环境变量中设置你的 API 秘钥(export SERP_API_KEY="your_key_here")。以下脚本发起一次有机网页搜索并打印排名结果:
import os
import httpx
API_KEY = os.environ.get("SERP_API_KEY")
response = httpx.post(
"https://serqo.io/v1/search",
headers={"x-api-key": API_KEY, "Content-Type": "application/json"},
json={
"q": "best python web scraping framework",
"engine": "google",
"type": "web",
"gl": "us",
"hl": "en",
},
timeout=10.0,
)
data = response.json()
for result in data["data"]["results"]:
print(f"#{result['position']} {result['title']}")
print(f" URL: {result['url']}")
print(f" 摘要: {result['snippet']}
")
第三步:实现深度搜索结果分页抓取
Google 搜索结果采用基于位移的分页机制。通过传入 start 参数获取后续结果页(如第一页 start=0,第二页 start=20),并根据 pagination.hasNext 判断是否还有后续页面:
import os
import httpx
def scrape_google_pages(query: str, max_pages: int = 3):
api_key = os.environ.get("SERP_API_KEY")
all_results = []
start = 0
with httpx.Client(timeout=15.0) as client:
for page in range(1, max_pages + 1):
res = client.post(
"https://serqo.io/v1/search",
headers={"x-api-key": api_key, "Content-Type": "application/json"},
json={"q": query, "engine": "google", "type": "web", "start": start},
)
payload = res.json()
results = payload.get("data", {}).get("results", [])
all_results.extend(results)
print(f"第 {page} 页抓取完成:获得 {len(results)} 条结果。")
pagination = payload.get("data", {}).get("pagination", {})
if not pagination.get("hasNext"):
break
start = pagination.get("nextStart", start + 20)
return all_results
results = scrape_google_pages("machine learning research papers", max_pages=2)
print(f"累计采集到 {len(results)} 条数据。")
第四步:从 SerpApi Python SDK 极简迁移
如果你的现有项目使用了 google-search-results(SerpApi 官方包),可以通过以下极简适配类无缝迁移,无需改动下游业务处理逻辑:
# 无缝替代 SerpApi GoogleSearch 对象的极简适配器
import requests
class SerqoGoogleSearch:
def __init__(self, params: dict):
self.params = params
self.api_key = params.pop("api_key", None)
def get_dict(self) -> dict:
payload = {
"q": self.params.get("q"),
"engine": "google",
"type": "web",
"gl": self.params.get("gl", "us"),
"hl": self.params.get("hl", "en"),
}
res = requests.post(
"https://serqo.io/v1/search",
headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
json=payload,
timeout=10,
)
return res.json().get("data", {})
# 调用方式与原版完全一致:
# search = SerqoGoogleSearch({"q": "best cloud hosting", "api_key": "YOUR_KEY"})
# data = search.get_dict()
第五步:在 Python 中抓取 Google 实时热搜与下拉长尾词
除网页搜索外,Serqo 还可以直接在 Python 中获取 Google 实时爆发热搜(Trends)与多轮联想词挖掘(Autocomplete):
import os
import requests
api_key = os.environ.get("SERP_API_KEY")
# 1. 获取 Google 实时爆发热搜
trends_res = requests.post(
"https://serqo.io/v1/trends",
headers={"x-api-key": api_key, "Content-Type": "application/json"},
json={"geo": "US", "category": "Technology", "period": "24h", "limit": 5},
)
for t in trends_res.json()["data"]["trends"]:
print(f"热搜榜 #{t['rank']}: {t['keyword']} (爆发增长 +{t['growth']}%, 搜索量 {t['searchVolume']})")
# 2. 26 字母 A-Z 全网长尾词挖掘
suggest_res = requests.post(
"https://serqo.io/v1/autocomplete",
headers={"x-api-key": api_key, "Content-Type": "application/json"},
json={"q": "serp api ", "strategy": "alphabet"},
)
suggestions = suggest_res.json()["data"]["suggestions"]
print(f"成功挖掘到 {len(suggestions)} 个独特长尾商机词。")
总结
无需再为住宅代理维护、验证码风控和频繁改版的 HTML 解析器心力交瘁。使用 Serqo,你的 Python 数据管道即可享有结构化 JSON、自动化住宅 IP 轮换与 2 秒级响应保障。套餐低至 /月且额度永久不过期,让数据采集成本始终完全可控。