ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何将 SearXNG 后备添加到您的搜索管道
教程

如何将 SearXNG 后备添加到您的搜索管道

向您的搜索管道添加免费的 SearXNG 回退,并在需要结构化数据时自动故障转移到 Scavio。包含 Python 代码。

获取免费API密钥API文档

SearXNG 为您提供免费的自托管搜索结果,但返回非结构化 HTML,没有一致的 JSON。混合方法使用 SearXNG 进行低优先级查询,并在您需要结构化数据、SERP 功能或保证正常运行时间时以 0.005 美元/请求故障转移到 Scavio。本教程构建了一个后备管道,该管道首先尝试 SearXNG,并在 SearXNG 返回不完整结果时升级到 Scavio。

前置条件

  • Python 3.8+
  • 请求库
  • 来自 scavio.dev 的 Scavio API 密钥
  • 启用 JSON 格式的 SearXNG 实例(本地或远程)

操作指南

步骤 1: 配置 SearXNG 和 Scavio 客户端

使用统一的界面设置两个搜索后端。

Python
import os, requests, time

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
SCAVIO_H = {'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'}
SEARXNG_URL = os.environ.get('SEARXNG_URL', 'http://localhost:8080')

def search_searxng(query):
    try:
        r = requests.get(f'{SEARXNG_URL}/search',
            params={'q': query, 'format': 'json', 'engines': 'google'},
            timeout=5)
        r.raise_for_status()
        data = r.json()
        return [{'title': r['title'], 'link': r['url'], 'snippet': r.get('content', '')}
                for r in data.get('results', [])[:10]]
    except Exception as e:
        print(f'SearXNG failed: {e}')
        return None

def search_scavio(query):
    r = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SCAVIO_H, json={'query': query, 'country_code': 'us'})
    return r.json()

print('Clients configured.')

步骤 2: 构建后备路由器

首先尝试SearXNG。如果结果缺失或不完整,请晋升至 Scadio。

Python
def search_with_fallback(query, need_structured=False, min_results=5):
    cost = 0.0
    source = 'searxng'
    if not need_structured:
        results = search_searxng(query)
        if results and len(results) >= min_results:
            return {'results': results, 'source': source, 'cost': cost}
        print(f'SearXNG returned {len(results) if results else 0} results, falling back to Scavio')

    source = 'scavio'
    cost = 0.005
    data = search_scavio(query)
    return {
        'results': data.get('organic_results', []),
        'source': source,
        'cost': cost,
        'serp_features': {
            'ai_overview': bool(data.get('ai_overview')),
            'answer_box': bool(data.get('answer_box')),
            'paa': len(data.get('related_questions', []))
        }
    }

r = search_with_fallback('best python web framework 2026')
print(f'Source: {r["source"]}, Results: {len(r["results"])}, Cost: ${r["cost"]:.3f}')

步骤 3: 添加健康检查和指标

跟踪 SearXNG 可用性和回退率以估算成本。

Python
from collections import Counter

stats = Counter()

def tracked_search(query, **kwargs):
    r = search_with_fallback(query, **kwargs)
    stats[r['source']] += 1
    stats['total_cost'] += r['cost']
    return r

queries = ['python web framework', 'best serp api', 'tiktok analytics tool',
           'react vs vue 2026', 'llm agent search']
for q in queries:
    r = tracked_search(q)
    print(f'  {q[:35]:35} -> {r["source"]:8} ({len(r["results"])} results)')

print(f'\nSearXNG hits: {stats["searxng"]}, Scavio fallbacks: {stats["scavio"]}')
print(f'Total cost: ${stats["total_cost"]:.3f}')
print(f'Savings vs all-Scavio: ${len(queries) * 0.005 - stats["total_cost"]:.3f}')

步骤 4: 强制使用 Scavio 进行结构化查询

有些查询总是需要结构化的 SERP 数据。直接路由那些。

Python
STRUCTURED_PATTERNS = ['price', 'cost', 'pricing', 'buy', 'vs ', 'compare']

def smart_search(query):
    need_structured = any(p in query.lower() for p in STRUCTURED_PATTERNS)
    r = tracked_search(query, need_structured=need_structured)
    if need_structured:
        print(f'  [STRUCTURED] {query[:40]} -> Scavio (SERP features: {r.get("serp_features", {})})')
    else:
        print(f'  [BASIC] {query[:40]} -> {r["source"]}')
    return r

smart_search('python tutorial')
smart_search('scavio vs serpapi pricing')
smart_search('buy noise canceling headphones')
print(f'Total cost: ${stats["total_cost"]:.3f}')

Python 示例

Python
import os, requests

SCAVIO_H = {'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'}
SEARXNG = os.environ.get('SEARXNG_URL', 'http://localhost:8080')

def search(query, force_scavio=False):
    if not force_scavio:
        try:
            r = requests.get(f'{SEARXNG}/search', params={'q': query, 'format': 'json'}, timeout=5)
            results = r.json().get('results', [])[:10]
            if len(results) >= 5:
                print(f'{query}: {len(results)} results via SearXNG (free)')
                return results
        except: pass
    data = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SCAVIO_H, json={'query': query, 'country_code': 'us'}).json()
    print(f'{query}: {len(data.get("organic_results", []))} results via Scavio ($0.005)')
    return data.get('organic_results', [])

search('python api tutorial')
search('serp api pricing comparison', force_scavio=True)

JavaScript 示例

JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
const SEARXNG = process.env.SEARXNG_URL || 'http://localhost:8080';

async function search(query, forceScavio = false) {
  if (!forceScavio) {
    try {
      const r = await fetch(`${SEARXNG}/search?q=${encodeURIComponent(query)}&format=json`,
        { signal: AbortSignal.timeout(5000) });
      const data = await r.json();
      if (data.results?.length >= 5) {
        console.log(`${query}: ${data.results.length} via SearXNG (free)`);
        return data.results.slice(0, 10);
      }
    } catch {}
  }
  const data = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST', headers: SH,
    body: JSON.stringify({ query, country_code: 'us' })
  }).then(r => r.json());
  console.log(`${query}: ${(data.organic_results||[]).length} via Scavio ($0.005)`);
  return data.organic_results || [];
}
search('python tutorial').then(() => search('serp api pricing', true)).catch(console.error);

预期输出

JSON
  python web framework               -> searxng  (8 results)
  best serp api                       -> scavio   (10 results)
  tiktok analytics tool               -> searxng  (7 results)
  react vs vue 2026                   -> searxng  (9 results)
  llm agent search                    -> scavio   (10 results)

SearXNG hits: 3, Scavio fallbacks: 2
Total cost: $0.010
Savings vs all-Scavio: $0.015

相关教程

  • 如何以编程方式比较 SERP API 定价模型
  • 如何优化人工智能代理的搜索预算
  • 如何使用搜索 API 构建自定义 SEO 仪表板

常见问题

大多数开发者在15到30分钟内完成本教程。您需要一个Scavio API密钥(免费套餐即可)和可用的Python或JavaScript环境。

Python 3.8+. 请求库. 来自 scavio.dev 的 Scavio API 密钥. 启用 JSON 格式的 SearXNG 实例(本地或远程). Scavio API密钥注册即送50个免费积分。

可以。免费套餐注册即送50个积分,完全足够完成本教程并构建一个可运行的原型解决方案。

Scavio提供原生LangChain包(langchain-scavio)、MCP服务器以及适用于任何HTTP客户端的REST API。本教程使用 the raw REST API, 但您可以根据需要适配您选择的框架。

相关资源

Use Case

SearXNG + API 混合搜索

Read more
Best Of

生产环境最佳SearXNG替换API(2026)

Read more
Best Of

生产环境最佳SearXNG替代方案(2026)

Read more
Glossary

搜索 API 供应商格局(2026)

Read more
Use Case

SearXNG API 迁移

Read more
Comparison

Scavio vs SearXNG (self-hosted)

Read more

开始构建

向您的搜索管道添加免费的 SearXNG 回退,并在需要结构化数据时自动故障转移到 Scavio。包含 Python 代码。

获取免费API密钥阅读文档
ScavioScavio

面向AI智能体的实时搜索API。搜索所有平台,不仅仅是Google。

产品

  • 功能
  • 定价
  • 控制台
  • 联盟计划

开发者

  • 文档
  • API参考
  • 快速开始
  • MCP集成
  • Python SDK

替代方案

  • Tavily替代方案
  • SerpAPI替代方案
  • Firecrawl替代方案
  • Exa替代方案

工具

  • JSON格式化
  • cURL转代码
  • Token计数器
  • 全部工具

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策