Python 3.10+ · BSD-3-Clause

Scrapling 自适应网页抓取框架

从单个请求到大规模爬取,一个库搞定一切。解析器自动学习网站变化,抓取器绕过反机器人系统,爬虫框架支持并发、暂停恢复与代理轮换。零妥协。

92%
测试覆盖率
10x
JSON 序列化
784x
快于 BS4
100%
类型覆盖
demo.py
from scrapling.fetchers import StealthyFetcher

# 隐蔽抓取 — 自动绕过 Cloudflare 等反机器人系统
page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)

# 自适应抓取 — 即使网站结构变化也能定位元素
products = page.css('.product', auto_save=True)
products = page.css('.product', adaptive=True)

安装指南

1

基础安装

仅解析器引擎及其依赖项

terminal
pip install scrapling
推荐
2

安装抓取器

包含所有抓取器、浏览器和系统依赖项

terminal
pip install "scrapling[fetchers]"

# 安装浏览器依赖
scrapling install           # 正常安装
scrapling install --force   # 强制重新安装
3

可选功能

[ai]
MCP 服务器
[shell]
交互式 Shell
[all]
全部安装
terminal
pip install "scrapling[ai]"      # MCP 服务器
pip install "scrapling[shell]"   # Shell 功能
pip install "scrapling[all]"     # 全部安装

Docker

terminal
docker pull pyd4vinci/scrapling
# 或从 GitHub 注册表
docker pull ghcr.io/d4vinci/scrapling:latest

提示 — 也可以在代码中安装浏览器依赖:

from scrapling.cli import install
install([], standalone_mode=False)            # 正常安装
install(["--force"], standalone_mode=False)    # 强制重新安装

快速入门

quick_start.py
from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher

# 隐蔽抓取
StealthyFetcher.adaptive = True
p = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)

# 自适应数据提取
products = p.css('.product', auto_save=True)    # 首次保存元素信息
products = p.css('.product', adaptive=True)     # 之后自适应查找
spider_demo.py
from scrapling.spiders import Spider, Response

class MySpider(Spider):
    name = "demo"
    start_urls = ["https://example.com/"]

    async def parse(self, response: Response):
        for item in response.css('.product'):
            yield {"title": item.css('h2::text').get()}

MySpider().start()

HTTP 抓取器

使用 FetcherFetcherSession 实现快速且隐蔽的 HTTP 请求

fetcher.py
from scrapling.fetchers import Fetcher, FetcherSession

# 持久化会话 — 模拟最新版 Chrome 的 TLS 指纹
with FetcherSession(impersonate='chrome') as session:
    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()

极速请求

高性能 HTTP 库,支持 HTTP/3 协议

TLS 指纹

模拟真实浏览器 TLS 指纹和请求头

会话持久化

跨请求管理 Cookie 和连接状态

隐身抓取器

使用 StealthyFetcher 绕过 Cloudflare Turnstile 等反机器人系统

stealthy.py
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')
data = page.css('#padded_content a').getall()

反机器人绕过 — 提供高级隐身功能和指纹欺骗,可自动绕过各种 Cloudflare Turnstile/拦截页面。

动态抓取器

使用 DynamicFetcher 实现完整浏览器自动化,支持 Playwright

dynamic.py
from scrapling.fetchers import DynamicFetcher, DynamicSession

# 持久化会话
with DynamicSession(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 = DynamicFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()

异步会话管理

所有抓取器完整支持异步,提供专用异步会话类

async_sessions.py
import asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession, AsyncDynamicSession

# FetcherSession 支持上下文感知,可在同步/异步模式下工作
async with FetcherSession(http3=True) as session:
    page1 = session.get('https://quotes.toscrape.com/')
    page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')

# 异步隐身会话 — 并发处理多个页面
async with AsyncStealthySession(max_pages=2) as session:
    tasks = []
    urls = ['https://example.com/page1', 'https://example.com/page2']

    for url in urls:
        task = session.fetch(url)
        tasks.append(task)

    print(session.get_pool_stats())    # 浏览器标签页池状态
    results = await asyncio.gather(*tasks)
    print(session.get_pool_stats())

基础爬虫

类 Scrapy 的 API,支持并发请求、分页跟踪和数据导出

quotes_spider.py
from scrapling.spiders import Spider, Request, 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"抓取了 {len(result.items)} 条引言")
result.items.to_json("quotes.json")    # 导出 JSON
result.items.to_jsonl("quotes.jsonl")  # 导出 JSONL

多会话爬虫

在单个爬虫中混合使用 HTTP 请求和隐身浏览器会话

multi_session.py
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:
                # 普通页面 → 快速 HTTP
                yield Request(link, sid="fast", callback=self.parse)

暂停与恢复

基于检查点的爬取持久化,Ctrl+C 优雅关闭,重启自动恢复

checkpoint.py
# 指定 crawldir 启用暂停/恢复
QuotesSpider(crawldir="./crawl_data").start()

# 按 Ctrl+C 优雅暂停 — 进度自动保存
# 再次运行时传入相同 crawldir,从停止处继续

流式模式 — 通过 async for item in spider.stream() 实时接收数据项,带实时统计。

选择器与导航

CSS、XPath、BeautifulSoup 风格、文本搜索等多种选择方式

selectors.py
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_by_text('quote', tag='div')        # 按文本查找

# DOM 导航
first_quote = page.css('.quote')[0]
quote_text = first_quote.css('.text::text').get()
author = first_quote.next_sibling.css('.author::text')  # 兄弟元素
parent = first_quote.parent                              # 父元素

# 元素相似性
similar = first_quote.find_similar()    # 相似元素
below = first_quote.below_elements()    # 下方元素
纯解析器
from scrapling.parser import Selector

# 直接解析 HTML,无需抓取网站
page = Selector("<html>...</html>")
# 使用完全相同的 API!

自适应抓取

智能相似度算法,在网站变化后自动重新定位元素

智能元素追踪

即使网站重新设计,也能通过相似度算法找到目标元素。

查找相似元素

自动定位具有相似结构和属性的其他元素。

adaptive.py
from scrapling.fetchers import StealthyFetcher

StealthyFetcher.adaptive = True
page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)

# 第一步:保存元素信息
products = page.css('.product', auto_save=True)

# 第二步:网站变化后,自适应查找
products = page.css('.product', adaptive=True)

命令行工具

无需编写代码即可抓取和提取网页内容

交互式 shell
# 启动交互式网页抓取 Shell
scrapling shell
提取命令
# 提取为 Markdown
scrapling extract get 'https://example.com' content.md

# 指定 CSS 选择器提取文本
scrapling extract get 'https://example.com' content.txt \
  --css-selector '#fromSkipToProducts' --impersonate 'chrome'

# 使用 DynamicFetcher
scrapling extract fetch 'https://example.com' content.md \
  --css-selector '#fromSkipToProducts' --no-headless

# 绕过 Cloudflare
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' \
  captchas.html --css-selector '#padded_content a' --solve-cloudflare
.txt
纯文本
.md
Markdown
.html
原始 HTML

性能基准

所有基准测试均为 100 次以上运行的平均值

文本提取速度

5000 个嵌套元素

Scrapling
2.02 ms
Parsel/Scrapy
2.04 ms
Raw Lxml
2.54 ms
PyQuery
~12x
Selectolax
~41x
BS4 + Lxml
~784x
BS4 + html5lib
~1679x

元素相似性与文本搜索

自适应元素查找

Scrapling
2.39 ms
AutoScraper
5.21x

核心特性

🕷️

类 Scrapy 爬虫 API

使用 start_urls、异步 parse 回调和 Request/Response 对象定义爬虫。

并发爬取

可配置的并发限制、按域名限速和下载延迟。

🔄

多会话支持

统一的 HTTP 和隐身浏览器接口,通过 ID 路由到不同会话。

📡

流式模式

实时流式接收数据项,带实时统计,适合 UI 和数据管道。

🛡️

反机器人绕过

自动检测和绕过 Cloudflare 等防护,支持自定义重试逻辑。

🔌

代理轮换

内置 ProxyRotator,支持循环或自定义轮换策略。

🤖

MCP 服务器

内置 MCP 服务器,AI 辅助网页抓取,减少 token 使用量。

📘

完整类型覆盖

完整类型提示,出色 IDE 支持,使用 PyRight 和 MyPy 扫描。