比 BS4 快 785 倍,Scrapling 从抓取到爬取装进一个库
Scrapling 是什么
Scrapling 是一个 Python Web 抓取框架,把快速 HTTP 请求、隐身浏览器、强大的解析和并发爬取整合进一个库。
你可以用它抓取静态页面、渲染 JavaScript、与网站交互,并从网站背后的 API 调用中提取数据。构建爬虫时,它提供可复用会话、代理轮换、自动重试、暂停/恢复和内置数据导出。
你可以从 Python、终端,或通过 MCP 服务器和 Agent Skill 从 AI agent 中使用它。从提取几个字段到把整个网站收集成干净的 Markdown,Scrapling 覆盖完整抓取工作流。
能做什么
- 抓取与交互:快速 HTTP 请求、隐身浏览器、JavaScript 渲染、Cloudflare Turnstile/Interstitial 处理、持久会话和后台 API 捕获。
- 解析与提取:CSS、XPath、文本和正则搜索、自适应元素跟踪、相似元素匹配,以及干净的 Markdown 输出。
- 爬取与导出:并发 spider、代理轮换、重试、AutoThrottle、暂停/恢复、流式处理、现成模板,以及 JSON/JSONL/CSV/XML 导出。
- 用 AI 或终端抓取:给 AI agent 使用的 MCP 服务器、Agent Skill、CLI 命令和交互式 shell。
先看两个例子
从单个页面开始
from scrapling.fetchers import Fetcher
page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
print(quotes)
用 spider 扩大规模
from scrapling.spiders import Spider, Response
class QuotesSpider(Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com/"]
async def parse(self, response: Response):
for quote in response.css('.quote'):
yield {
"text": quote.css('.text::text').get(),
"author": quote.css('.author::text').get(),
}
result = QuotesSpider().start()
print(len(result.items))
result.items.to_json("quotes.json")
这段代码会打印 10,并把引言和作者保存到 quotes.json。
核心功能
Spiders:完整的爬取框架
- 🕷️ 类 Scrapy 的 Spider API:用 start_urls、异步 parse 回调和 Request/Response 对象定义 spider。
- ⚡ 并发爬取:可配置并发上限、按域名限流和下载延迟。
- 🔄 多会话支持:在单个 spider 中统一使用 HTTP 请求和隐身无头浏览器,按会话 ID 路由请求。
- 💾 暂停与恢复:用 crawldir 保存待处理请求和已见 URL。按 Ctrl+C 优雅停止,再用同一目录重启恢复。
- 📡 流式模式:通过 async for item in spider.stream() 在抓取项到达时流式输出,并带实时统计,适合 UI、管道和长时间爬取。
- 🛡️ 拦截请求检测:自动检测并重试被拦截的请求,逻辑可自定义。
- 🚦 AutoThrottle:不用再猜延迟。spider 会根据网站响应速度自动调整每个域名的延迟,当网站开始拦截或限流时把延迟翻倍(或按 Retry-After 要求等待),网站恢复后再加速。
- 🤖 Robots.txt 合规:可选 robots_txt_obey 标志,遵守 Disallow、Crawl-delay 和 Request-rate 指令,并按域名缓存。
- 🧪 开发模式:首次运行把响应缓存到磁盘,后续运行重放,迭代 parse() 逻辑时不用反复请求目标服务器。
- 🧩 现成 Spider 模板:用 CrawlSpider 做基于规则的链接跟进,用 SitemapSpider 做由 sitemap/robots.txt 驱动的爬取,用 XMLFeedSpider/CSVFeedSpider 迭代 XML/RSS 和 CSV 源,用 ShopifySpider 从公开 Shopify 商店收集产品,每个变体一条 item,省去样板代码。
- 🔗 链接提取:独立的 LinkExtractor 原语,支持 allow/deny 模式、域名过滤、CSS/XPath 范围、扩展名过滤和规范化,可在模板内或单独使用。
- 📦 内置导出:通过 hooks 和你自己的 pipeline 或内置 JSON/JSONL/CSV/XML 导出器导出结果,使用 result.items.to_json()、to_jsonl()、to_csv() 和 to_xml()。
支持会话的高级网站抓取
- HTTP 请求:用 Fetcher 类发起快速、隐身的 HTTP 请求。可模拟浏览器的 TLS 指纹、headers,并支持 HTTP/3。
- 动态加载:通过 StealthyFetcher 类做完整浏览器自动化,抓取动态网站,支持 Playwright 的 Chromium 和 Google 的 Chrome。
- 反机器人绕过:StealthyFetcher 和指纹伪装提供高级隐身能力。可通过自动化轻松绕过所有类型的 Cloudflare Turnstile/Interstitial。
- 会话管理:用 FetcherSession 和 StealthySession 类支持持久会话,跨请求管理 cookie 和状态。
- 代理轮换:内置 ProxyRotator,支持循环或自定义轮换策略,适用于所有会话类型,并可按请求覆盖代理。
- 域名与广告拦截:在基于浏览器的抓取器中,拦截对特定域名(及其子域名)的请求,或启用内置广告拦截(约 3,500 个已知广告/追踪域名)。
- DNS 泄漏防护:可选的 DNS-over-HTTPS 支持,通过 Cloudflare 的 DoH 路由 DNS 查询,防止使用代理时发生 DNS 泄漏。
- 远程浏览器:不本地启动浏览器,而是通过 CDP 连接一个已运行的浏览器,用 cdp_url 指定,无论它在本机、另一台主机还是托管浏览器服务商。也可以用 executable_path 让任何浏览器抓取器指向你自己的 Chromium 构建。
- 后台 API 捕获:在浏览器会话上启用 record_requests=True,然后用 session.network.search(limit=None) 搜索保存的响应。这样可以在不再次发送请求的情况下读取页面加载期间的 API 数据和 HTTP 错误。历史记录有上限,并保存文本响应体。
- 异步支持:所有抓取器和专用异步会话类都完整支持异步。
解析与数据提取
- 🔄 智能元素跟踪:网站变化后,用智能相似度算法重新定位元素。
- 🎯 智能灵活选择:CSS 选择器、XPath 选择器、基于过滤器的搜索、文本搜索、正则搜索等。
- 🔍 查找相似元素:自动定位与已找到元素相似的元素。
AI 功能
- 🤖 MCP 服务器:让 AI 聊天机器人和 agent(Claude/Cursor 等)通过 Scrapling 抓取,支持 HTTP 请求、浏览器操作、截图、已保存的登录状态和后台 API 响应。它使用我们的隐身浏览器和合适的工具,让合适的 AI 模型在工作时绕过它遇到的任何 CAPTCHA(更不用说我们的 Cloudflare 求解器)。它使用多种方法减少发送给模型的内容、拦截广告,并防止 Prompt-Injection。还包括通过 CDP 的远程浏览器和带身份验证选项的 HTTP 传输。(演示视频)
- 🧠 Agent Skill:一个可直接安装的 Agent Skill,教编码 agent 整个库的用法,让它们用 Scrapling 写出的代码符合当前 API,而不是靠猜。
- 📚 适合 RAG 的 Markdown:用一行 page.markdown() 把任何页面变成干净、经过清理、适合 LLM 的 Markdown,或用 ContentSpider 模板把整个网站爬取成 Markdown 语料库,全程不需要 LLM 参与。(文档)
高性能与经受过实战检验的架构
- 🚀 极快:性能经过优化,超过大多数 Python 抓取库。
- 🔋 内存高效:优化的数据结构和懒加载带来极低内存占用。
- ⚡ 快速 JSON 序列化:比标准库快 10 倍。
- 🏗️ 经受过实战检验:Scrapling 不仅有 92% 测试覆盖率和完整类型提示覆盖,过去一年里还被数百名 Web 抓取开发者每天使用。
对开发者和爬虫友好的体验
- 🎯 交互式 Web 抓取 Shell:可选内置 IPython shell,集成 Scrapling、快捷键和新工具,加速 Web 抓取脚本开发,比如把 curl 请求转成 Scrapling 请求,以及在浏览器中查看请求结果。
- 🚀 直接从终端使用:也可以选择用 Scrapling 抓取 URL,一行代码都不用写。
- 🛠️ 丰富的导航 API:高级 DOM 遍历,支持父级、兄弟和子级导航方法。
- 🧬 增强文本处理:内置正则、清理方法和优化字符串操作。
- 📝 自动生成选择器:为任何元素生成稳健的 CSS/XPath 选择器。
- 🔌 熟悉的 API:类似 Scrapy/BeautifulSoup,使用与 Scrapy/Parsel 相同的伪元素。
- 🤝 可直接集成 Scrapy:已经在用 Scrapy?用 scrapling_response 装饰任何回调,就能用 Scrapling 的解析器解析你已经抓取的响应,无需重写。
- 📘 完整类型覆盖:完整类型提示带来出色的 IDE 支持和代码补全。每次变更都会用 PyRight 和 MyPy 自动扫描整个代码库。
- 🔋 现成 Docker 镜像:每次发布都会自动构建并推送包含所有浏览器的 Docker 镜像。
快速上手
下面快速展示 Scrapling 能做什么,不深入细节。
基础用法:带会话支持的 HTTP 请求
from scrapling.fetchers import Fetcher, FetcherSession
with FetcherSession(impersonate='chrome') as session: # 使用最新版 Chrome 的 TLS 指纹
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
quotes = page.css('.quote .text::text').getall()
# 或者使用一次性请求
page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
高级隐身模式
from scrapling.fetchers import StealthyFetcher, StealthySession
with StealthySession(headless=True, solve_cloudflare=True) as session: # 浏览器保持打开,直到你完成
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
data = page.css('#padded_content a').getall()
# 或使用一次性请求方式:为这个请求打开浏览器,完成后关闭
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare', solve_cloudflare=True)
data = page.css('#padded_content a').getall()
完整浏览器自动化
from scrapling.fetchers import StealthyFetcher, StealthySession
with StealthySession(headless=True, disable_resources=False, network_idle=True) as session: # 浏览器保持打开,直到你完成
page = session.fetch('https://quotes.toscrape.com/', load_dom=False)
data = page.xpath('//span[@class="text"]/text()').getall() # 如果喜欢,也可以用 XPath 选择器
# 或使用一次性请求方式:为这个请求打开浏览器,完成后关闭
page = StealthyFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()
爬虫:并发、多会话与暂停/恢复
用并发请求、多种会话类型和暂停/恢复构建完整爬虫:
from scrapling.spiders import Spider, Response
class QuotesSpider(Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com/"]
concurrent_requests = 10
async def parse(self, response: Response):
for quote in response.css('.quote'):
yield {
"text": quote.css('.text::text').get(),
"author": quote.css('.author::text').get(),
}
next_page = response.css('.next a')
if next_page:
yield response.follow(next_page[0].attrib['href'])
result = QuotesSpider().start()
print(f"Scraped {len(result.items)} quotes")
result.items.to_json("quotes.json")
在单个 spider 里使用多种会话类型:
from scrapling.spiders import Spider, Request, Response
from scrapling.fetchers import FetcherSession, AsyncStealthySession
class MultiSessionSpider(Spider):
name = "multi"
start_urls = ["https://example.com/"]
def configure_sessions(self, manager):
manager.add("fast", FetcherSession(impersonate="chrome"))
manager.add("stealth", AsyncStealthySession(headless=True), lazy=True)
async def parse(self, response: Response):
for link in response.css('a::attr(href)').getall():
# 把受保护的页面交给隐身会话
if "protected" in link:
yield Request(link, sid="stealth")
else:
yield Request(link, sid="fast", callback=self.parse) # 显式 callback
用检查点暂停和恢复长时间爬取,可以这样运行 spider:
QuotesSpider(crawldir="./crawl_data").start()
设置 crawldir 后,按 Ctrl+C 保存待处理请求和已见 URL。用同一 crawldir 重启即可恢复。抓取到的 item 要单独保存。
或者干脆不写爬取逻辑,用现成模板,比如拉取整个 Shopify 商店目录:
from scrapling.spiders import ShopifySpider
class MyStore(ShopifySpider):
target_website = "example.com"
result = MyStore().start() # 商店中的每个产品,每个变体一条 item
该模板通过公开的 collection 端点读取产品,每个变体一条 item。
高级解析与导航
from scrapling.fetchers import Fetcher
# 富元素选择和导航
page = Fetcher.get('https://quotes.toscrape.com/')
# 用多种选择方法获取引言
quotes = page.css('.quote') # CSS 选择器
quotes = page.xpath('//div[@class="quote"]') # XPath
quotes = page.find_all('div', {'class': 'quote'}) # BeautifulSoup 风格
# 等同于
quotes = page.find_all('div', class_='quote')
quotes = page.find_all(['div'], class_='quote')
quotes = page.find_all(class_='quote') # 以此类推...
# 按文本内容查找元素
quotes = page.find_by_text('Albert Einstein', first_match=False)
# 高级导航
quote_text = page.css('.quote')[0].css('.text::text').get()
quote_texts = page.css('.quote').css('.text::text').getall() # 链式选择器
first_quote = page.css('.quote')[0]
author = first_quote.css('.author::text').get()
next_quote = first_quote.next
parent_container = first_quote.parent
# 元素关系和相似性
similar_elements = first_quote.find_similar()
below_elements = first_quote.below_elements
如果不想抓取网站,也可以直接使用解析器:
from scrapling.parser import Selector
page = Selector("<html>...</html>")
用法完全一致。
异步会话管理示例
import asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession
async def main():
async with FetcherSession(http3=True) as http_session: # `FetcherSession` 是上下文感知的,可用于同步/异步模式
page1 = await http_session.get('https://quotes.toscrape.com/')
page2 = await http_session.get('https://quotes.toscrape.com/page/2/', impersonate='chrome')
print(len(page1.css('.quote')), len(page2.css('.quote')))
async with AsyncStealthySession(max_pages=2) as browser_session:
urls = ['https://quotes.toscrape.com/js/', 'https://quotes.toscrape.com/js/page/2/']
pages = await asyncio.gather(*(browser_session.fetch(url, wait_selector='.quote') for url in urls))
print([len(page.css('.quote')) for page in pages])
asyncio.run(main())
CLI 与交互式 Shell
Scrapling 包含强大的命令行接口。
启动交互式 Web 抓取 shell:
pip install "scrapling[shell]"
scrapling shell
不用编程就能把页面直接提取到文件。用 --css-selector 选择内容,或用 --ai-targeted 选择并清理正文内容。文件扩展名用 .txt 表示文本,.md 表示 Markdown,.html 表示 HTML。
scrapling extract get 'https://quotes.toscrape.com/' quotes.md
scrapling extract get 'https://quotes.toscrape.com/' quotes.txt --css-selector '.quote' --impersonate 'chrome'
scrapling extract fetch 'https://quotes.toscrape.com/js/' quotes.md --css-selector '.quote' --wait-selector '.quote' --no-headless
scrapling extract fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
注意:还有更多功能,但本页保持简洁,包括 MCP 服务器和交互式 Web 抓取 Shell。完整文档请查看项目文档。
性能基准
Scrapling 不仅强大,也很快。下面的基准测试把 Scrapling 的解析器与其他流行库的最新版本进行比较。
文本提取速度测试(5000 个嵌套元素):
| # | 库 | 时间 (ms) | 相对 Scrapling |
|---|---|---|---|
| 1 | Scrapling | 1.99 | 1.0x |
| 2 | Parsel/Scrapy | 2.06 | 1.035 |
| 3 | Raw Lxml | 2.56 | 1.286 |
| 4 | PyQuery | 23.98 | ~12x |
| 5 | Selectolax | 197.02 | ~99x |
| 6 | MechanicalSoup | 1545.15 | ~776.5x |
| 7 | BS4 with Lxml | 1562.1 | ~785.0x |
| 8 | BS4 with html5lib | 3412.73 | ~1714.9x |
元素相似性与文本搜索性能:
Scrapling 的自适应元素查找能力显著优于替代方案:
| 库 | 时间 (ms) | 相对 Scrapling |
|---|---|---|
| Scrapling | 2.3 | 1.0x |
| AutoScraper | 12.58 | 5.47x |
所有基准测试都是 100+ 次运行的平均值。方法说明见 benchmarks.py。
安装
Scrapling 要求 Python 3.10 或更高版本:
pip install scrapling
注意:这个安装只包含解析器引擎及其依赖,不包含任何抓取器或命令行依赖。因此只这样安装后,导入 scrapling.fetchers 或 scrapling.spiders(如上面示例所示)会抛出 ModuleNotFoundError。如果要使用任何抓取器或 spider,先按下面说明安装抓取器依赖。
可选依赖
如果要使用下面的额外功能、抓取器或其类,需要安装抓取器依赖和浏览器依赖:
pip install "scrapling[fetchers]"
scrapling install # 正常安装
scrapling install --force # 强制重装
这会下载所有浏览器及其系统依赖和指纹操作依赖。
也可以不从命令行,而是在代码中安装:
from scrapling.cli import install
install([], standalone_mode=False) # 正常安装
install(["--force"], standalone_mode=False) # 强制重装
额外功能:
- 安装 MCP 服务器功能:
pip install "scrapling[ai]"
- 安装构建 RAG 系统所需的依赖:
pip install "scrapling[rag]"
- 安装 shell 功能(Web 抓取 shell 和 extract 命令):
pip install "scrapling[shell]"
- 安装所有内容:
pip install "scrapling[all]"
需要浏览器抓取器时运行 scrapling install。HTTP 请求不需要安装浏览器。
Docker
也可以从 DockerHub 拉取包含所有额外功能和浏览器的 Docker 镜像:
docker pull pyd4vinci/scrapling
或从 GitHub registry 下载:
docker pull ghcr.io/d4vinci/scrapling:latest
该镜像通过 GitHub Actions 使用仓库的主分支自动构建并推送。
贡献
欢迎贡献。开始前请阅读贡献指南。
免责声明
注意:本库仅用于教育和研究目的。使用本库即表示你同意遵守当地和国际的数据抓取及隐私法律。作者和贡献者不对本软件的任何滥用负责。始终尊重网站的服务条款和 robots.txt 文件。