返回资讯中心
外部精选
大数据
#数据科学#机器学习

用 Python 和 Olostep 批量抓取 1 万页 MDN 文档,3 分钟完成

来源标题:Web Scraping 7,000 Pages in 3 Minutes with Python and Olostep

开发者用 Olostep Batch API 在约 3 分钟内抓取了 10,000 个 MDN 文档页面,但并非全部成功:最终保存 9,938 页,缺失 62 页。该测试使用 Python 3.13.15 和 Olostep SDK 1.2.2,将页面内容下载为 Markdown 并核对完成数量,说明验证结果与抓取速度同样重要。

KDnuggetsAbid Ali Awan2026/11/5 · 12 天前17 分钟阅读

以下正文由 AI 翻译自 KDnuggets(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。

有一点很重要:批次完成并不代表每个页面都成功保存。在我的测试中,10,000 个页面里有 9,938 个保存成功,另有 62 个缺失。正因如此,验证结果和抓取速度同样重要,尤其是在构建可靠的数据管道时。

我们将使用 Olostep Batch API 抓取 10,000 个 MDN 文档页面,把内容下载为 Markdown 文件,并验证最终成功收集了多少页面。

本次实验使用 Python 3.13.15 和 Olostep SDK 1.2.2。整个过程分为六步,从环境搭建一直到检查最终结果。你需要一个 Olostep API key 才能跟着操作。你可以把它设为环境变量(OLOSTEP_API_KEY),也可以在提示时安全输入。

注意:提交新批次会消耗 API credits,运行代码前请确认账户余额充足。

首先打开一个新的 Jupyter Notebook,或启动本教程附带的 notebook。在第一个单元格中安装 Olostep Python SDK,以及用于获取 MDN sitemap 的 requests 和用于跟踪抓取进度的 tqdm。

%pip -q install olostep==1.2.2 requests tqdm

  1. 配置客户端

接下来,我们用 API key 初始化 Olostep 客户端,创建一个文件夹存放抓取数据,并定义几个用于保存和校验结果的辅助函数。我们还会针对 SDK 1.2.2 中一个响应处理问题加一个小变通方案,确保能顺利检查批次状态而不报错。

import asyncio, csv, gzip, hashlib, json, os, random, time from datetime import datetime, timezone from getpass import getpass from pathlib import Path from xml.etree import ElementTree as ET import requests from olostep import AsyncOlostep from olostep.errors import OlostepClientError_ResponseValidationFailed from olostep.models.response import BatchInfoResponse from tqdm import tqdm N = 10000 MAX_WAIT_SECONDS = 2400 DATA = Path("data"); DATA.mkdir(exist_ok=True) client = AsyncOlostep(api_key=os.getenv("OLOSTEP_API_KEY") or getpass("Olostep API key: ")) def write_json(path, value): path.write_text(json.dumps(value, indent=2), encoding="utf-8") def valid_file(path): try: return path.is_file() and bool(path.read_text(encoding="utf-8").strip()) except (OSError, UnicodeError): return False async def batch_info(batch_id): try: return await client.batches.info(batch_id) except OlostepClientError_ResponseValidationFailed as error: return BatchInfoResponse.model_validate({"parser": "none", **json.loads(error.response.body)})

  1. 构建 URL 数据集

现在,我们下载 MDN sitemap,并随机挑选 10,000 个不重复的文档页面用于实验。

代码会把这些 URL 保存到 CSV 文件中,这样就能复用同一份列表,不必重复下载。它还会检查重复项,确保我们使用的是正确的数据集。

source = "https://developer.mozilla.org/sitemaps/en-us/sitemap.xml.gz" if not (DATA / "urls.csv").exists(): response = requests.get(source, timeout=60); response.raise_for_status() payload = response.content xml = gzip.decompress(payload) if payload.startswith(b"\x1f\x8b") else payload (DATA / "mdn_sitemap.xml").write_bytes(xml) ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"} nodes = ET.fromstring(xml).findall("s:url", ns) urls = sorted({node.findtext("s:loc", namespaces=ns) for node in nodes}) urls = [url for url in urls if url and url.startswith("https://developer.mozilla.org/en-US/docs/")] random.Random(42).shuffle(urls) assert len(urls) >= N, f"Only {len(urls)} unique documentation URLs available." with (DATA / "urls.csv").open("w", newline="", encoding="utf-8") as f: writer = csv.writer(f); writer.writerow(["url"]); writer.writerows([url] for url in urls[:N]) write_json(DATA / "dataset.json", {"source": source, "downloaded_utc": datetime.now(timezone.utc).isoformat(), "available_urls": len(urls), "selected_urls": N, "random_seed": 42}) with (DATA / "urls.csv").open(encoding="utf-8", newline="") as f: urls = [row["url"] for row in csv.DictReader(f)] assert len(urls) == len(set(urls)) == N fingerprint = hashlib.sha256("\n".join(urls).encode()).hexdigest() expected = {f"{i:05d}": url for i, url in enumerate(urls)} print(f"Ready: {len(urls):,} unique URLs; source: {source}")

输出: Ready: 10,000 unique URLs; source: https://developer.mozilla.org/sitemaps/en-us/sitemap.xml.gz

输出确认我们的数据集包含 10,000 个不重复的 URL,可以进行批量抓取了。

接下来,我们把全部 10,000 个 URL 作为单个批次提交给 Olostep,并用进度条监控抓取进度。

代码还会保存 batch ID,这样即使过程中断,也能恢复同一个任务,而不必从头开始。

checkpoint = Path("batch.json") resumed = checkpoint.exists() if resumed: run = json.loads(checkpoint.read_text(encoding="utf-8")) assert run["urls_sha256"] == fingerprint, "URL list changed; preserve the checkpoint before starting another batch." else: started = time.time() batch = await client.batches.create(urls=[{"url": url, "custom_id": key} for key, url in expected.items()]) run = {"batch_id": batch.id, "requested": N, "urls_sha256": fingerprint, "started_wall": started} write_json(checkpoint, run) OUT = Path("output") / run["batch_id"]; OUT.mkdir(parents=True, exist_ok=True) print("Resuming" if resumed else "Submitted", run["batch_id"]) wait_started = time.monotonic() with tqdm(total=N, desc="Scraping", unit="page") as bar: while True: info = await batch_info(run["batch_id"]) bar.update(max(0, info.completed_urls - bar.n)) write_json(OUT / "progress.json", {"phase": "scraping

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →