跳转到主要内容
通过 Olostep 的 /v1/crawls 端点,你可以爬取一个网站并获取所有页面的内容。
  • 爬取一个网站并获取所有子页面的内容(或限制爬取的深度)
  • 使用特殊模式爬取特定页面(例如 /blog/**
  • 传递一个 webhook_url 以在爬取完成时收到通知
  • 搜索查询以仅查找特定页面并按相关性排序
有关 API 详细信息,请参阅 爬取端点 API 参考

安装

# pip install requests

import requests

开始爬取

提供起始 URL,包含/排除 URL 模式,以及 max_pages。可选项:max_depthinclude_externalinclude_subdomainsearch_querytop_nwebhook_urltimeout
import time, json

API_URL = 'https://api.olostep.com'
API_KEY = '<YOUR_API_KEY>'
HEADERS = { 
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {API_KEY}' 
}

data = {
  "start_url": "https://sugarbooandco.com",
  "max_pages": 100,
  "include_urls": ["/**"],
  "exclude_urls": ["/collections/**"],
  "include_external": False
}

res = requests.post(f"{API_URL}/v1/crawls", headers=HEADERS, json=data)
crawl = res.json()
print(json.dumps(crawl, indent=2))
由于 Olostep 中的所有内容都是对象,你将收到一个 crawl 对象作为响应。crawl 对象有一些属性,比如 idstatus,你可以用来跟踪爬取。

检查爬取状态

轮询爬取以跟踪进度,直到 statuscompleted
import time

def get_crawl_info(crawl_id):
    return requests.get(f'{API_URL}/v1/crawls/{crawl_id}', headers=HEADERS).json()

crawl_id = crawl['id']
while True:
    info = get_crawl_info(crawl_id)
    print(info['status'], info.get('pages_count'))
    if info['status'] == 'completed':
        break
    time.sleep(5)
或者,你可以在开始爬取时传递一个 webhook_url,以便在爬取完成时收到通知。

列出页面(使用游标分页/流式传输)

获取页面并使用 cursorlimit 进行迭代。在爬取 in_progresscompleted 时工作。
def get_pages(crawl_id, cursor=None, limit=10, search_query=None):
    params = { 
        'cursor': cursor, 
        'limit': limit
    }
    return requests.get(f'{API_URL}/v1/crawls/{crawl_id}/pages', headers=HEADERS, params=params).json()

cursor = 0
while True:
    page_batch = get_pages(crawl_id, cursor=cursor, limit=10)
    for page in page_batch['pages']:
        print(page['url'], page['retrieve_id'])
    if 'cursor' not in page_batch:
        break
    cursor = page_batch['cursor']
    time.sleep(5)

搜索查询(限制为前 N 个相关)

在开始时使用 search_query,并可选择使用 search_query 过滤列表。使用 top_n 限制每页探索。
data = {
  "start_url": "https://sugarbooandco.com",
  "max_pages": 100,
  "include_urls": ["/**"],
  "search_query": "contact us",
  "top_n": 5
}
crawl = requests.post(f'{API_URL}/v1/crawls', headers=HEADERS, json=data).json()
pages = requests.get(f"{API_URL}/v1/crawls/{crawl['id']}/pages", headers=HEADERS, params={'search_query': 'contact us'}).json()
print(len(pages['pages']))

获取内容

使用每个页面的 retrieve_id/v1/retrieve 来获取 html_content 和/或 markdown_content
def retrieve_content(retrieve_id):
    return requests.get(f"{API_URL}/v1/retrieve", headers=HEADERS, params={"retrieve_id": retrieve_id}).json()

for page in get_pages(crawl['id'], limit=5)['pages']:
    retrieved = retrieve_content(page['retrieve_id'])
    print(retrieved.get('markdown_content'))

注意事项

  • 分页是基于游标的;重复请求直到 cursor 不存在。
  • /v1/crawls/{crawl_id}/pages 上的内容字段已弃用;请使用 /v1/retrieve
  • Webhooks:设置 webhook_url 以在爬取完成时接收 POST。

价格

每爬取一页耗费 1 个信用点。