API 文档
SearchCans SERP API 和 Reader API 完整指南
API 概览 - 双引擎平台
SearchCans 为您提供两个强大的API接口:
快速开始
统一响应格式
所有 API 响应都遵循统一的 JSON 格式:
{
"code": 200, // 200为成功,其他为失败
"msg": "", // 失败原因
"data": any // 返回数据
}
身份验证
SearchCans API 使用 Bearer Token 进行身份验证。在请求头中包含您的 API 密钥:
Authorization: Bearer YOUR_API_KEY
SERP API - Bing搜索接口
接口地址
POST https://searchcans.youxikuang.cn/api/search
GET https://searchcans.youxikuang.cn/api/search
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| s | string | 是 | 搜索关键词 |
| t | string | 是 | 搜索引擎类型:bing。注意:中文站由于地区限制仅支持bing |
| d | number | 否 | 接口最大等待时间(毫秒),默认10000。推荐:10000-15000毫秒以获得稳定结果 |
| p | number | 否 | 页码,默认为1 |
请求示例
curl -X POST https://searchcans.youxikuang.cn/api/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"s": "artificial intelligence",
"t": "bing",
"p": 1,
"d": 10000
}'响应示例
{
"code": 0,
"msg": "成功",
"data": [
{
"title": "搜索结果标题",
"url": "https://example.com",
"content": "搜索结果摘要内容..."
}
]
}
生产环境代码示例
批量关键词搜索工具,带自动重试和结果保存功能。
Python - 批量搜索工具
import requests
import json
import time
import os
from datetime import datetime
# 配置
API_KEY = "YOUR_API_KEY"
API_URL = "https://searchcans.youxikuang.cn/api/search"
KEYWORDS_FILE = "keywords.txt" # 每行一个关键词
OUTPUT_DIR = "serp_results"
SEARCH_ENGINE = "bing" # 中文站仅支持bing
MAX_RETRIES = 3
def load_keywords(filepath):
"""从文件加载关键词"""
if not os.path.exists(filepath):
print(f"❌ 错误:找不到 {filepath}")
return []
keywords = []
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
keyword = line.strip()
if keyword and not keyword.startswith('#'):
keywords.append(keyword)
return keywords
def search_keyword(keyword, page=1):
"""使用SERP API搜索单个关键词"""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"s": keyword,
"t": SEARCH_ENGINE,
"d": 10000, # 10秒超时
"p": page
}
try:
response = requests.post(API_URL, headers=headers, json=payload, timeout=15)
result = response.json()
if result.get("code") == 0:
print(f"✅ 成功:{len(result.get('data', []))} 条结果")
return result
else:
print(f"❌ 失败:{result.get('msg')}")
return None
except Exception as e:
print(f"❌ 错误:{e}")
return None
def search_with_retry(keyword):
"""带自动重试的搜索"""
for attempt in range(MAX_RETRIES):
if attempt > 0:
print(f" 🔄 重试 {attempt}/{MAX_RETRIES-1}...")
time.sleep(2)
result = search_keyword(keyword)
if result:
return result
print(f" ❌ {MAX_RETRIES} 次尝试后仍然失败")
return None
def save_result(keyword, result, output_dir):
"""保存搜索结果"""
# 创建安全的文件名
safe_name = "".join(c if c.isalnum() or c in (' ', '-', '_') else '_' for c in keyword)
safe_name = safe_name[:50]
# 保存为单独的JSON文件
json_file = os.path.join(output_dir, f"{safe_name}.json")
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
# 同时保存到汇总JSONL文件
jsonl_file = os.path.join(output_dir, "all_results.jsonl")
with open(jsonl_file, 'a', encoding='utf-8') as f:
record = {
"keyword": keyword,
"timestamp": datetime.now().isoformat(),
"result": result
}
f.write(json.dumps(record, ensure_ascii=False) + "\n")
print(f" 💾 已保存:{safe_name}.json")
def main():
"""主执行函数"""
print("🚀 SearchCans SERP API 批量搜索工具")
print("=" * 60)
# 加载关键词
keywords = load_keywords(KEYWORDS_FILE)
if not keywords:
return
total = len(keywords)
print(f"📄 已加载 {total} 个关键词\n")
# 创建输出目录
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir = f"{OUTPUT_DIR}_{timestamp}"
os.makedirs(output_dir, exist_ok=True)
print(f"📂 输出目录:{output_dir}/\n")
# 处理每个关键词
completed = 0
for index, keyword in enumerate(keywords, 1):
print(f"[{index}/{total}] 关键词:{keyword}")
result = search_with_retry(keyword)
if result:
save_result(keyword, result, output_dir)
# 提取并显示URL
urls = [item.get("url", "") for item in result.get("data", [])]
if urls:
print(f" 🔗 找到 {len(urls)} 个链接")
for i, url in enumerate(urls[:3], 1):
print(f" {i}. {url[:70]}...")
completed += 1
# 速率限制
if index < total:
time.sleep(1)
# 统计摘要
print("\n" + "=" * 60)
print(f"📊 摘要:{completed}/{total} 个成功")
print(f"📁 结果已保存到:{output_dir}/")
if __name__ == "__main__":
main()
使用方法:
- 创建
keywords.txt文件,每行一个关键词 - 将
YOUR_API_KEY替换为实际的API密钥 - 运行:
python serp_search.py - 结果保存为单独JSON文件 + 汇总JSONL文件
功能特性:失败自动重试、进度跟踪、批量结果导出。
相关指南与教程
教程文章:
同时提供:
- • Reader API →
- 将任何URL转换为干净的LLM-Ready Markdown。专为RAG管道和AI训练数据优化。
Reader API - URL转Markdown转换
为什么选择Reader API?LLM-Ready解决方案
将任何URL转换为干净、结构化、LLM-Ready的Markdown - AI应用的通用格式:
✓ 简单集成 - 发送URL,获取内容
✓ 稳定可靠 - 99.65%可用性保障
✓ JavaScript支持 - 自动处理动态内容
✓ 持续更新 - 无需修改代码
接口地址
POST https://searchcans.youxikuang.cn/api/url
GET https://searchcans.youxikuang.cn/api/url
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| s | string | 是 | 要提取的网页URL |
| t | string | 是 | 类型,固定值:url |
| w | number | 否 | 打开URL等待时间(毫秒),默认3000。推荐:JavaScript密集型网站3000-5000毫秒 |
| d | number | 否 | 接口最大等待时间(毫秒),默认20000。推荐:复杂页面20000-30000毫秒 |
| b | boolean | 否 | 是否需要浏览器打开,默认true。对于JavaScript密集型网站(SPA、React、Vue应用)设为true |
| proxy | number | 否 | 绕过模式(高级功能):设为1启用。采用增强型网络架构突破URL访问限制,成功率达98%。消耗5积分(普通模式2积分)。建议先尝试普通模式,失败时再启用。 |
请求示例
curl -X POST https://searchcans.youxikuang.cn/api/url \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"s": "https://example.com",
"t": "url",
"w": 3000,
"d": 20000,
"b": true
}'💡 绕过模式(高级功能)
当您遇到某些URL访问限制时,可以通过添加 proxy: 1 参数启用绕过模式。
什么是绕过模式?
绕过模式采用增强型网络架构突破目标URL的访问限制。成功率高达98%,适用于对标准请求设有防护的站点。
积分消耗:
- • 普通模式:每次请求消耗 2积分
- • 绕过模式:每次请求消耗 5积分
💰 最佳实践(节省成本):
始终先尝试普通模式,仅在收到错误响应时再启用绕过模式。这种方式既能最大化成功率,又能有效控制成本。
示例代码(Python):
# 先尝试普通模式(2积分)
payload = {
"s": "https://example.com",
"t": "url",
"b": True,
"w": 3000,
"d": 20000
}
response = requests.post(api_url, json=payload, headers=headers)
result = response.json()
# 如果失败,使用绕过模式重试(5积分)
if result.get("code") != 0:
print("普通模式失败,启用绕过模式...")
payload["proxy"] = 1 # 启用增强访问
response = requests.post(api_url, json=payload, headers=headers)
result = response.json() 响应示例
{
"code": 0,
"msg": "成功",
"data": {
"title": "文章标题",
"description": "文章描述或meta描述",
"markdown": "# 标题\n\n干净的markdown内容...",
"html": "<html>...</html>"
}
}
// 注意:某些情况下,'data' 可能是需要解析的JSON字符串:
// const parsedData = JSON.parse(response.data);
💡 参数使用提示
- w(等待时间):对于JavaScript密集型网站(SPA、React、Vue应用),建议增加到3000-5000毫秒。默认3000毫秒适合大多数现代网站。
- d(超时时间):对于加载缓慢的复杂页面,建议设置为20000-30000毫秒。如果遇到超时错误,请增加此值。
- b(浏览器模式):
- •
true:完整的JavaScript渲染,较慢但完整(2-5秒)。推荐用于SPA和动态内容。 - •
false:快速静态提取,可能遗漏JS生成的内容(0.5-1秒)。适用于简单的HTML页面。
- •
生产环境代码示例(含错误处理)
Python
import requests
import json
import time
def extract_content(url, retry=3):
"""
使用最佳设置和错误处理提取内容
"""
api_url = "https://searchcans.youxikuang.cn/api/url"
headers = {
"Authorization": f"Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
payload = {
"s": url,
"t": "url",
"w": 3000, # 等待3秒以完成JS渲染
"d": 20000, # 最大超时20秒
"b": True # 启用浏览器模式
}
for attempt in range(retry):
try:
# 设置超时略高于'd'参数
response = requests.post(
api_url,
headers=headers,
json=payload,
timeout=25
)
result = response.json()
if result["code"] == 0:
# 解析数据(可能是字符串或对象)
data = result["data"]
if isinstance(data, str):
data = json.loads(data)
return {
"title": data.get("title", ""),
"markdown": data.get("markdown", ""),
"html": data.get("html", ""),
"description": data.get("description", "")
}
else:
print(f"API错误:{result.get('msg')}")
if attempt < retry - 1:
time.sleep(2) # 重试前等待
continue
return None
except requests.exceptions.Timeout:
print(f"第{attempt + 1}/{retry}次尝试超时")
if attempt < retry - 1:
time.sleep(2)
continue
return None
except Exception as e:
print(f"错误:{str(e)}")
return None
return None
# 使用示例
if __name__ == "__main__":
url = "https://example.com/article"
content = extract_content(url)
if content:
print(f"✅ 标题:{content['title']}")
print(f"📄 内容长度:{len(content['markdown'])} 字符")
# 保存到文件
with open("output.md", "w", encoding="utf-8") as f:
f.write(f"# {content['title']}\n\n")
f.write(content['markdown'])
print("✅ 已保存到 output.md")
else:
print("❌ 提取失败")
💡 完整数据结构
Reader API 返回丰富的多格式数据结构:
{
"title": "文章标题", // 页面标题
"description": "Meta描述", // SEO描述
"markdown": "# 干净内容...", // LLM-Ready Markdown
"html": "<html>...</html>" // 完整HTML源码
} 保存为多种格式:
📄 Markdown (.md)
非常适合LLM训练、RAG管道和文档存储
🌐 HTML (.html)
完整页面源码,用于存档和分析
📦 JSON (.json)
包含所有元数据的结构化数据,适合数据库存储
专业建议:保存全部三种格式以获得最大灵活性。Markdown用于AI,HTML用于备份,JSON用于元数据。
⚠️ 常见错误及解决方案
错误:"Timeout" 或 "Request timeout"
- • 将
d参数增加到25000-30000毫秒 - • 检查目标网站是否可访问
- • 确保代码的超时时间高于
d参数
错误:"数据解析失败"
- • 检查
response.data是否为字符串,使用JSON.parse() - • 在访问字段前验证响应结构
问题:"内容缺失或markdown为空"
- • 设置
b: true以启用浏览器渲染 - • 对于JavaScript密集型网站,将
w增加到5000毫秒 - • 注意:某些网站具有高级反爬虫保护机制。对于反爬建设度高的网站,我们不保证能够100%成功提取内容。
相关指南与教程
同时提供:
- • 搜索API (SERP API) →
- 实时获取Bing搜索结果。适合SEO工具和市场研究。
响应代码与错误处理
所有 API 响应都在 JSON 正文中包含一个 code 字段,用于指示请求状态。了解这些代码有助于您有效处理错误。
| 代码 | 类型 | 描述 | 解决方案 |
|---|---|---|---|
| 200 | 成功 | 请求已成功处理 | 无需操作 |
| -1001 | 响应超时 | API 请求超过了等待时间 | 增加 d 参数值(例如 15000-20000ms),或检查目标网站可访问性 |
| 443 | 连接错误 | SSL/网络端口连接问题 | 验证网络连接,检查防火墙设置,确保 SSL 证书有效 |
| 10054 | 连接重置 | 远程主机强制关闭了连接 | 重试请求,检查目标网站是否阻止请求,考虑在请求之间添加延迟 |
| 401 | 未授权 | API 密钥无效或缺失 | 检查 Authorization 请求头中的 API 密钥,从控制台获取新密钥 |
| 403 | 禁止访问 | 权限不足或配额已用尽 | 在控制台检查账户配额,如需升级套餐 |
| 429 | 超出速率限制 | 短时间内请求过多 | 实施请求限流,在请求之间添加延迟,或升级到更高级别的套餐 |
| 500 | 内部服务器错误 | 服务器遇到意外错误 | 几秒后重试,如持续出现请联系技术支持 |
💡 错误处理最佳实践
- 在处理
data之前始终检查code字段 - 对超时错误(-1001)实施指数退避的重试逻辑
- 记录错误代码和消息以便调试
- 根据您的使用场景设置适当的超时值(SERP API:10-15秒,Reader API:15-30秒)
技术支持
如果您在使用过程中遇到任何问题,请通过以下方式联系我们: