以编程方式获取 Google 搜索结果是 SEO 工具、研究管道和 AI 代理的核心要求。传统方法——管理代理、轮换用户代理和解析原始 HTML——脆弱且昂贵。 Scavio API 提供单个 POST 端点,该端点返回结构化 JSON,包括有机结果、特色片段、知识图和 People Also Ask 数据。本教程将逐步介绍如何使用 requests 库在 Python 中进行身份验证、形成请求和解析响应。
前置条件
- 安装了 Python 3.8 或更高版本
- 安装请求库(pip install requests)
- 来自 scavio.dev 的 Scavio API 密钥
- 基本熟悉 Python 字典和 JSON
操作指南
步骤 1: 安装请求库
如果您尚未安装 requests,请将其添加到您的环境中。这是本教程所需的唯一依赖项。
pip install requests步骤 2: 设置您的 API 密钥
将您的 Scavio API 密钥存储在环境变量中,而不是对其进行硬编码。这使得凭证不受源代码控制。
import os
API_KEY = os.environ.get("SCAVIO_API_KEY", "your_scavio_api_key")步骤 3: 发送搜索请求
使用您的查询和国家/地区代码 POST 到 Scavio 端点。响应是一个包含有机结果和 SERP 功能的 JSON 对象。
import requests
response = requests.post(
"https://api.scavio.dev/api/v1/search",
headers={"x-api-key": API_KEY},
json={"query": "best python web frameworks", "country_code": "us"}
)
data = response.json()步骤 4: 解析并打印有机结果
Organic_results 键包含结果对象的列表。每个都有标题、链接和片段字段。
for result in data.get("organic_results", []):
print(result["title"])
print(result["link"])
print(result.get("snippet", ""))
print()Python 示例
import os
import requests
API_KEY = os.environ.get("SCAVIO_API_KEY", "your_scavio_api_key")
ENDPOINT = "https://api.scavio.dev/api/v1/search"
def search_google(query: str, country: str = "us") -> dict:
response = requests.post(
ENDPOINT,
headers={"x-api-key": API_KEY, "Content-Type": "application/json"},
json={"query": query, "country_code": country}
)
response.raise_for_status()
return response.json()
def main():
results = search_google("best python web frameworks")
organic = results.get("organic_results", [])
print(f"Found {len(organic)} results")
for r in organic[:5]:
print(f"- {r['title']}")
print(f" {r['link']}")
if __name__ == "__main__":
main()JavaScript 示例
const API_KEY = process.env.SCAVIO_API_KEY || "your_scavio_api_key";
const ENDPOINT = "https://api.scavio.dev/api/v1/search";
async function searchGoogle(query, country = "us") {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json"
},
body: JSON.stringify({ query, country_code: country })
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function main() {
const results = await searchGoogle("best python web frameworks");
const organic = results.organic_results || [];
console.log(`Found ${organic.length} results`);
organic.slice(0, 5).forEach(r => {
console.log(`- ${r.title}`);
console.log(` ${r.link}`);
});
}
main().catch(console.error);预期输出
{
"search_metadata": { "query": "best python web frameworks", "country_code": "us" },
"organic_results": [
{
"position": 1,
"title": "Top Python Web Frameworks in 2026",
"link": "https://example.com/python-frameworks",
"snippet": "Django, FastAPI, and Flask remain the top choices..."
},
{
"position": 2,
"title": "FastAPI vs Django: Which Should You Use?",
"link": "https://example.com/fastapi-vs-django",
"snippet": "FastAPI is ideal for async microservices..."
}
]
}