小马的 AI 工具集

网页爬取

自适应网页爬取框架,自动绕过反爬并在页面改版后重定位元素

网页爬取
类型 69,672 星标 更新 2026-07-15 许可 BSD-3-Clause 原仓库 主页

Scrapling Poster
为现代网页轻松实现数据抓取

D4Vinci%2FScrapling | Trendshift
العربيه | Español | Português (Brasil) | Français | Deutsch | 简体中文 | 日本語 | Русский | 한국어
Tests PyPI version PyPI package downloads Static Badge OpenClaw Skill
Discord X (formerly Twitter) Follow
Supported Python versions

选择方法 · 获取器 · 爬虫框架 · 代理轮换 · CLI · MCP

Scrapling 是一个自适应 Web 抓取框架,能从单次请求覆盖到全规模爬取。

它的解析器能够学习网站变化,在页面更新时自动重新定位你的元素。它的获取器开箱即可绕过 Cloudflare Turnstile 等反机器人系统。它的爬虫框架让你能够扩展到并发、多会话的爬取,支持暂停/恢复和自动代理轮换——仅需几行 Python 代码。一个库,零妥协。

支持实时统计和流式输出的极速爬取。由 Web 抓取者为 Web 抓取者和普通用户打造,每个人都能找到适合自己的功能。

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)                                         # 之后如果网站结构发生变化,传入 `adaptive=True` 即可找到它们!

或者扩展到全规模爬取

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()

在 DataImpulse,我们专注于为您的业务开发定制代理服务。从任何地方发起请求,收集数据,并通过我们的高级代理享受快速连接。

白金赞助商

Proxidize 为爬虫、浏览器自动化、SEO 监控、AI 代理和数据收集提供移动和住宅代理。使用代码 scrapling20 可享 8 折优惠
ColdProxy 提供住宅和数据中心代理,用于稳定的 Web 抓取、公共数据收集以及覆盖 195+ 个国家的定向测试。
Scrapling 处理 Cloudflare Turnstile。对于企业级防护, Hyper Solutions 提供 API 端点,为 AkamaiDataDomeKasadaIncapsula 生成有效的反机器人令牌。简单 API 调用,无需浏览器自动化。
Evomi :住宅代理,$0.49/GB 起。爬虫浏览器完全模拟 Chromium,配备住宅 IP、自动验证码破解和反机器人绕过。
Scraper API 可轻松获得结果。提供 MCP 和 N8N 集成。
TikHub.io 提供 900+ 个稳定 API,覆盖 16+ 个平台(包括 TikTok、X、YouTube 和 Instagram),拥有 4000 万+ 数据集。
还提供 折扣 AI 模型——Claude、GPT、GEMINI 等,最高优惠 71%。
合上您的笔记本电脑。您的爬虫继续运行。
PetroSky VPS——专为不间断自动化打造的云服务器。Windows 和 Linux 机器,完全控制。每月 €6.99 起。
Web Scraping Club(2025 年 11 月)阅读 Scrapling 的完整评测,这是 #1 专注 Web 抓取的新闻简报。
Swiftproxy 提供可扩展的住宅代理,拥有 8000 万+ IP,覆盖 195+ 个国家,提供快速、可靠的连接、自动轮换和强大的反封锁性能。提供免费试用。
NodeMaven——可靠的代理提供商,拥有市场上最高质量的 IP。使用促销代码 SCRAPLING35 可享受代理 35% 折扣。

想在这里展示您的广告?点击此处

赞助商

想在这里展示您的广告?点击此处并选择适合您的层级!


主要特性

Spiders - 完整的爬取框架

  • 🕷️ Scrapy 风格的 Spider API: 定义包含 start_urls、异步 parse 回调以及 Request/Response 对象的爬虫。
  • 并发爬取: 可配置的并发限制、每域限速和下载延迟。
  • 🔄 多会话支持: 单个爬虫内统一接口支持 HTTP 请求和隐身无头浏览器——通过 ID 将请求路由到不同会话。
  • 💾 暂停与恢复: 基于检查点的爬取持久化。按 Ctrl+C 优雅关闭;重启后从上次中断处继续。
  • 📡 流式模式: 通过 async for item in spider.stream() 实时流式输出抓取的项目,附带实时统计——非常适合 UI、管道和长时间运行的任务。
  • 🛡️ 被屏蔽请求检测: 自动检测并重试被屏蔽的请求,支持自定义逻辑。
  • 🤖 Robots.txt 合规: 可选 robots_txt_obey 标志,遵守 DisallowCrawl-delayRequest-rate 指令,支持每域缓存。
  • 🧪 开发模式: 首次运行时将响应缓存到磁盘,后续运行回放缓存——无需重复请求目标服务器即可迭代 parse() 逻辑。
  • 📦 内置导出: 通过钩子与自定义管道导出结果,或使用内置的 JSON/JSONL 导出(result.items.to_json() / result.items.to_jsonl())。

高级网站抓取(支持会话)

  • HTTP 请求: 使用 Fetcher 类实现快速且隐身的 HTTP 请求。可模拟浏览器的 TLS 指纹、请求头,并支持 HTTP/3。
  • 动态加载: 通过支持 Playwright 的 Chromium 和 Google Chrome 的 DynamicFetcher 类,利用完整浏览器自动化获取动态网站。
  • 反爬绕过: 使用 StealthyFetcher 和指纹伪装的高级隐身功能。可轻松绕过所有类型的 Cloudflare Turnstile/Interstitial 验证。
  • 会话管理: 提供 FetcherSessionStealthySessionDynamicSession 类,支持持久的 Cookie 和状态管理。
  • 代理轮换: 内置 ProxyRotator,支持循环或自定义轮换策略,适用于所有会话类型,并提供单请求代理覆盖。
  • 域名与广告屏蔽: 在基于浏览器的 fetcher 中屏蔽对特定域名(及其子域)的请求,或启用内置广告屏蔽(约 3500 个已知广告/跟踪域名)。
  • DNS 泄漏防护: 可选 DNS-over-HTTPS 支持,通过 Cloudflare 的 DoH 路由 DNS 查询,防止在使用代理时发生 DNS 泄漏。
  • 异步支持: 所有 fetcher 均完全支持异步,并提供专用的异步会话类。

自适应抓取与 AI 集成

  • 🔄 智能元素追踪: 网站变动后,使用智能相似度算法重新定位元素。
  • 🎯 智能灵活选择: CSS 选择器、XPath 选择器、基于过滤器的搜索、文本搜索、正则搜索等。
  • 🔍 查找相似元素: 自动定位与已发现元素相似的其它元素。
  • 🤖 可供 AI 使用的 MCP 服务器: 内置 MCP 服务器,专为 AI 辅助的网页抓取和数据提取而设计。该 MCP 服务器配备强大、自定义的能力,利用 Scrapling 提取目标内容后传给 AI(Claude/Cursor 等),从而加速操作并降低 token 消耗以减少成本。(演示视频

高性能与久经考验的架构

  • 🚀 闪电般快速: 优化后的性能超越大多数 Python 抓取库。
  • 🔋 内存高效: 优化的数据结构和惰性加载,内存占用极小。
  • 快速 JSON 序列化: 比标准库快 10 倍。
  • 🏗️ 久经考验: Scrapling 不仅拥有 92% 的测试覆盖率和完整的类型提示覆盖,在过去一年中还被数百个网页抓取工具日常使用。

开发者/网络爬虫友好体验

  • 🎯 交互式网页抓取 Shell: 可选内置 IPython Shell,集成 Scrapling、快捷键和新工具,加速脚本开发,例如将 curl 请求转换为 Scrapling 请求并在浏览器中查看请求结果。
  • 🚀 直接从终端使用: 可选择无需编写任何代码即可使用 Scrapling 抓取 URL!
  • 🛠️ 丰富的导航 API: 提供父节点、兄弟节点和子节点导航方法的高级 DOM 遍历。
  • 🧬 增强的文本处理: 内置正则、清理方法和优化的字符串操作。
  • 📝 自动选择器生成: 为任意元素生成健壮的 CSS/XPath 选择器。
  • 🔌 熟悉的 API: 类似 Scrapy/BeautifulSoup,使用与 Scrapy/Parsel 相同的伪元素。
  • 📘 完整的类型覆盖: 完整的类型提示,提供出色的 IDE 支持和代码补全。每次变更都会自动使用 PyRightMyPy 扫描整个代码库。
  • 🔋 现成的 Docker 镜像: 每次发布时,自动构建并推送包含所有浏览器的 Docker 镜像。

快速开始

让我们在不深入探讨的情况下,快速了解 Scrapling 能做什么。

基本用法

支持会话的 HTTP 请求

from scrapling.fetchers import Fetcher, FetcherSession

with FetcherSession(impersonate='chrome') as session:  # Use latest version of Chrome's TLS fingerprint
    page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
    quotes = page.css('.quote .text::text').getall()

# Or use one-off requests
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:  # Keep the browser open until you finish
    page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
    data = page.css('#padded_content a').getall()

# Or use one-off request style, it opens the browser for this request, then closes it after finishing
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
data = page.css('#padded_content a').getall()

完整浏览器自动化

from scrapling.fetchers import DynamicFetcher, DynamicSession

with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:  # Keep the browser open until you finish
    page = session.fetch('https://quotes.toscrape.com/', load_dom=False)
    data = page.xpath('//span[@class="text"]/text()').getall()  # XPath selector if you prefer it

# Or use one-off request style, it opens the browser for this request, then closes it after finishing
page = DynamicFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()

蜘蛛(Spiders)

使用并发请求、多种会话类型以及暂停/恢复功能构建完整的爬虫:

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")

在单个蜘蛛中使用多种会话类型:

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)  # 显式回调

通过以下方式运行蜘蛛,利用检查点暂停和恢复长时间爬取:

QuotesSpider(crawldir="./crawl_data").start()

按 Ctrl+C 优雅暂停——进度会自动保存。稍后再次启动蜘蛛时,传入相同的 crawldir,它将从停止的地方恢复。

高级解析与导航

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('quote', tag='div')

# 高级导航
quote_text = page.css('.quote')[0].css('.text::text').get()
quote_text = page.css('.quote').css('.text::text').getall()  # 链式选择器
first_quote = page.css('.quote')[0]
author = first_quote.next_sibling.css('.author::text')
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, AsyncDynamicSession

async with FetcherSession(http3=True) as session:  # `FetcherSession` 是上下文感知的,可以同时在同步/异步模式下工作
    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())

CLI 与交互式 Shell

Scrapling 包含一个强大的命令行界面:

asciicast

启动交互式 Web 抓取 Shell

scrapling shell

无需编程即可直接将页面提取到文件(默认提取 body 标签内的内容)。如果输出文件以 .txt 结尾,则会提取目标的文本内容;如果以 .md 结尾,则会生成 HTML 内容的 Markdown 表示;如果以 .html 结尾,则是 HTML 内容本身。

scrapling extract get 'https://example.com' content.md
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome'  # 所有匹配 CSS 选择器 '#fromSkipToProducts' 的元素
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare

[!NOTE] 还有很多其他功能,但我们希望保持本页简洁,包括 MCP 服务器和交互式 Web 抓取 Shell。请查看完整文档 这里

性能基准测试

Scrapling 不仅功能强大,而且速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了比较。

文本提取速度测试(5000 个嵌套元素)

#时间 (ms)对比 Scrapling
1Scrapling1.981.0x
2Parsel/Scrapy1.991.005
3Raw Lxml2.481.253
4PyQuery23.15~12x
5Selectolax196.09~99x
6MechanicalSoup1531.24~773.4x
7BS4 with Lxml1535.19~775.3x
8BS4 with html5lib3388.16~1711.2x

元素相似性与文本搜索性能

Scrapling 的自适应元素查找能力显著优于其他方案:

时间 (ms)对比 Scrapling
Scrapling2.291.0x
AutoScraper12.465.441x

所有基准测试均为 100 次以上运行的平均值。参见 benchmarks.py 了解方法。

安装

Scrapling 需要 Python 3.10 或更高版本:

pip install scrapling

[!IMPORTANT] 此安装仅包含解析器引擎及其依赖项,不包含任何抓取器或命令行依赖项。因此,仅凭此安装,从 scrapling.fetchersscrapling.spiders 导入任何内容(如上述示例)将引发 ModuleNotFoundError。如果您将使用任何抓取器或蜘蛛,请先按如下所示安装抓取器依赖项。

可选依赖

  1. 如果你打算使用以下任何额外功能、取器(fetchers)及其类,你需要按如下方式安装取器的依赖及其浏览器依赖:

    pip install "scrapling[fetchers]"
    
    scrapling install           # 正常安装
    scrapling install  --force  # 强制重新安装

    这会下载所有浏览器及其系统依赖和指纹操作依赖。

    或者,你可以从代码中安装它们,而不是运行这样的命令:

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

    • 安装 MCP 服务器功能:
      pip install "scrapling[ai]"
    • 安装 Shell 功能(Web Scraping shell 和 extract 命令):
      pip install "scrapling[shell]"
    • 安装全部功能:
      pip install "scrapling[all]"

    请记住,在安装任何这些额外的包之后,你需要使用 scrapling install 安装浏览器依赖(如果尚未安装)。

Docker

你还可以通过以下命令从 DockerHub 安装包含所有额外功能和浏览器的 Docker 镜像:

docker pull pyd4vinci/scrapling

或者从 GitHub 注册表下载:

docker pull ghcr.io/d4vinci/scrapling:latest

此镜像使用 GitHub Actions 和仓库的主分支自动构建并推送。

贡献

我们欢迎贡献!请在开始之前阅读我们的贡献指南

免责声明

[!CAUTION] 本库仅供教育和研究目的使用。使用本库即表示您同意遵守当地和国际的数据抓取和隐私法律。作者和贡献者不对任何滥用本软件的行为负责。请始终尊重网站的 service terms 和 robots.txt 文件。

🎓 引用

如果您在研究工作中使用了我们的库,请使用以下参考文献引用我们:

  @misc{scrapling,
    author = {Karim Shoair},
    title = {Scrapling},
    year = {2024},
    url = {https://github.com/D4Vinci/Scrapling},
    note = {An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!}
  }

许可证

本作品采用 BSD-3-Clause 许可证。

致谢

本项目包含改编自以下项目的代码:

  • Parsel(BSD 许可证)—— 用于 translator 子模块

由 Karim Shoair 用心设计与制作 ❤️

在 GitHub 查看完整项目