搜索 API 使用示例
本文档提供了详细的搜索 API 使用示例,帮助您快速上手并掌握各种搜索功能。
🚀 快速开始
基本搜索示例
import requests
import json
def search_web(query, api_key, count=10):
"""
执行网页搜索
参数:
query (str): 搜索关键词
api_key (str): API密钥
count (int): 返回结果数量,默认10
"""
url = "https://platform.kuaisou.com/api/web-search"
# 构建请求数据
payload = json.dumps({
"query": query,
"offset": 1,
"count": count
})
# 设置请求头
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
# 发送请求
response = requests.post(url, headers=headers, data=payload)
# 检查响应状态
if response.status_code == 200:
return response.json()
else:
raise Exception(f"搜索请求失败: {response.status_code} - {response.text}")
# 使用示例
if __name__ == "__main__":
# 设置API密钥
API_KEY = "sk-********" # 替换为您的API密钥
try:
# 执行搜索
results = search_web(
query="人工智能发展趋势",
api_key=API_KEY,
count=10
)
# 打印结果
print(json.dumps(results, indent=2, ensure_ascii=False))
except Exception as e:
print(f"发生错误: {str(e)}")
📝 详细示例
1. 时间范围搜索
# 搜索一周内的内容
results = search_web(
query="人工智能",
api_key=API_KEY,
count=20,
freshness="oneWeek" # 一周内的结果
)
# 搜索指定日期范围
results = search_web(
query="科技新闻",
api_key=API_KEY,
count=10,
freshness="2024-01-01..2024-03-20" # 指定日期范围
)
2. 分页搜索
def search_with_pagination(query, api_key, total_pages=3):
"""
分页搜索示例
"""
all_results = []
for page in range(1, total_pages + 1):
payload = json.dumps({
"query": query,
"offset": page,
"count": 10
})
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
response = requests.post(
"https://platform.kuaisou.com/api/web-search",
headers=headers,
data=payload
)
if response.status_code == 200:
data = response.json()
all_results.extend(data.get('webPages', {}).get('value', []))
else:
print(f"第{page}页请求失败: {response.status_code}")
return all_results
# 使用分页搜索
results = search_with_pagination("Python教程", API_KEY, 3)
print(f"总共获取到 {len(results)} 条结果")
3. 错误处理示例
def safe_search(query, api_key, max_retries=3):
"""
带错误处理的搜索函数
"""
for attempt in range(max_retries):
try:
payload = json.dumps({
"query": query,
"count": 10
})
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
response = requests.post(
"https://platform.kuaisou.com/api/web-search",
headers=headers,
data=payload,
timeout=10 # 设置超时时间
)
if response.status_code == 200:
return response.json()
elif response.status_code == 401:
raise Exception("API密钥无效")
elif response.status_code == 429:
print(f"请求频率过高,等待重试... (尝试 {attempt + 1}/{max_retries})")
time.sleep(2 ** attempt) # 指数退避
else:
raise Exception(f"请求失败: {response.status_code}")
except requests.exceptions.Timeout:
print(f"请求超时,重试中... (尝试 {attempt + 1}/{max_retries})")
except Exception as e:
print(f"发生错误: {str(e)}")
if attempt == max_retries - 1:
raise
raise Exception("所有重试都失败了")
# 使用安全搜索
try:
results = safe_search("机器学习", API_KEY)
print("搜索成功!")
except Exception as e:
print(f"搜索失败: {str(e)}")
4. 结果处理示例
def process_search_results(results):
"""
处理搜索结果的示例
"""
if not results or 'webPages' not in results:
return []
web_pages = results['webPages'].get('value', [])
processed_results = []
for page in web_pages:
processed_result = {
'title': page.get('name', ''),
'url': page.get('url', ''),
'snippet': page.get('snippet', ''),
'summary': page.get('summary', ''),
'site_name': page.get('siteName', ''),
'publish_time': page.get('datePublished', ''),
}
processed_results.append(processed_result)
return processed_results
def display_results(results):
"""
美化显示搜索结果
"""
processed = process_search_results(results)
print(f"\n🔍 搜索结果 ({len(processed)} 条)")
print("=" * 60)
for i, result in enumerate(processed, 1):
print(f"\n📄 结果 {i}")
print(f"标题: {result['title']}")
print(f"网址: {result['url']}")
print(f"摘要: {result['snippet'][:100]}...")
print(f"网站: {result['site_name']}")
print(f"发布时间: {result['publish_time']}")
print("-" * 40)
# 使用结果处理
results = search_web("区块链技术", API_KEY)
display_results(results)
🔧 cURL 示例
基本搜索请求
curl -X POST "https://platform.kuaisou.com/api/web-search" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "人工智能发展趋势",
"count": 10,
"offset": 1
}'
带时间范围的搜索
curl -X POST "https://platform.kuaisou.com/api/web-search" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "科技新闻",
"count": 20,
"freshness": "oneWeek"
}'
📊 响应处理
响应格式示例
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "人工智能"
},
"webPages": {
"webSearchUrl": "https://platform.kuaisou.com/api/web-search?query=人工智能",
"totalEstimatedMatches": 1000,
"value": [
{
"id": "https://platform.kuaisou.com/api/v1/#WebPages.0",
"name": "人工智能 - 维基百科",
"url": "https://zh.wikipedia.org/wiki/人工智能",
"displayUrl": "zh.wikipedia.org/wiki/人工智能",
"snippet": "人工智能(Artificial Intelligence,缩写为AI)是指由人制造出来的系统所表现出的智能。",
"summary": "人工智能是计算机科学的一个分支,它企图了解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器。",
}
]
}
}
💡 最佳实践
1. 性能优化
- 合理设置
count参数,避免一次性获取过多数据 - 使用
freshness参数限制时间范围,提高搜索精度 - 实现请求缓存,避免重复搜索相同关键词
2. 错误处理
- 始终检查响应状态码
- 实现重试机制处理临时错误
- 监控API调用频率,避免超出限制
3. 用户体验
- 提供搜索进度提示
- 实现搜索结果缓存
- 添加搜索建议功能