网页爬取
自适应网页爬取框架,自动绕过反爬并在页面改版后重定位元素
面向现代 Web 的轻松网页抓取
العربيه | Español | Português (Brasil) | Français | Deutsch | 简体中文 | 日本語 | Русский | 한국어
选择方法 · 获取器 · 爬虫 · 代理轮换 · CLI · MCP
Scrapling 是一个自适应 Web 抓取框架,可处理从单个请求到全量爬取的一切任务。
它的解析器能从网站变化中学习,并在页面更新时自动重新定位你的元素。其获取器能开箱即用地绕过 Cloudflare Turnstile 等反机器人系统。而其爬虫框架让你能够扩展到并发、多会话的爬取,支持暂停/恢复和自动代理轮换——仅需几行 Python 代码。一个库,零妥协。
支持实时统计和流式传输的极速爬取。由网页抓取者为网页抓取者和普通用户打造,每个人都有适合自己的功能。
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()
白金赞助商
|
NodeMaven - 可靠的代理提供商,提供市场上最高质量的 IP。使用优惠码 SCRAPLING35 可享代理 35% 折扣。 |
|
Proxidize 提供移动和住宅代理,用于抓取、浏览器自动化、SEO 监控、AI 代理和数据收集。 使用代码 scrapling20 可享 20% 优惠。 |
|
ColdProxy 提供住宅和数据中心代理,用于稳定的网页抓取、公共数据收集以及覆盖 195+ 个国家的地理定位测试。 |
|
Scrapling 处理 Cloudflare Turnstile。对于企业级防护, Hyper Solutions 提供 API 端点,可生成适用于 Akamai、DataDome、Kasada 和 Incapsula 的有效反机器人令牌。简单的 API 调用,无需浏览器自动化。 |
|
Evomi
: 住宅代理,从 $0.49/GB 起。抓取浏览器,完全伪造的 Chromium、住宅 IP、自动 CAPTCHA 解决和反机器人绕过。 Scraper API 可轻松获得结果。提供 MCP 和 N8N 集成。 |
|
TikHub.io 提供 900+ 个稳定 API,覆盖 TikTok、X、YouTube 和 Instagram 等 16+ 平台,拥有 4000 万+ 数据集。 还提供 折扣 AI 模型 - Claude、GPT、GEMINI 等,最高可享 71% 优惠。 |
|
合上你的笔记本。你的爬虫会继续运行。 PetroSky VPS - 专为不间断自动化设计的云服务器。Windows 和 Linux 机器,完全控制。€6.99/月起。 |
|
阅读 The Web Scraping Club 上关于 Scrapling 的完整评测(2025 年 11 月),这是专注于网页抓取的头号新闻通讯。 |
|
Swiftproxy 提供可扩展的住宅代理,拥有 8000 万+ IP,覆盖 195+ 个国家,提供快速、可靠的连接、自动轮换和强大的防屏蔽性能。提供免费试用。 |
想要在这里展示您的广告吗?点击此处
赞助商
想要在这里展示您的广告吗?点击此处选择适合您的层级!
主要特性
Spiders - 完整的爬虫框架
- 🕷️ Scrapy-like Spider API: 使用
start_urls、异步parse回调以及Request/Response对象来定义爬虫。 - ⚡ Concurrent Crawling: 可配置的并发限制、按域限速和下载延迟。
- 🔄 Multi-Session Support: 在单个爬虫中统一支持HTTP请求和隐身无头浏览器 - 通过ID将请求路由到不同会话。
- 💾 Pause & Resume: 基于检查点的爬取持久化。按Ctrl+C优雅关闭;重启后从断点继续。
- 📡 Streaming Mode: 通过
async for item in spider.stream()实时流式输出抓取到的项目,并带有实时统计 - 适用于UI、管道和长时间爬取。 - 🛡️ Blocked Request Detection: 自动检测并重试被屏蔽的请求,逻辑可自定义。
- 🚦 AutoThrottle: 无需猜测延迟。爬虫根据网站响应速度自动调整每个域名的延迟,当网站开始屏蔽或限速时,将延迟加倍(或等待
Retry-After指定的时间),一旦停止限制则恢复速度。 - 🤖 Robots.txt Compliance: 可选的
robots_txt_obey标志,遵循Disallow、Crawl-delay和Request-rate指令,并按域缓存。 - 🧪 Development Mode: 首次运行时将响应缓存到磁盘,后续运行重放 - 可迭代
parse()逻辑而无需重新请求目标服务器。 - 🧩 Ready-made Spider Templates: 使用
CrawlSpider进行基于规则的链接跟踪,SitemapSpider进行站点地图/robots.txt驱动的爬取,ShopifySpider通过其JSON API从任何Shopify商店提取所有产品,每个变体一个项目,从而跳过样板代码。 - 🔗 Link Extraction: 独立的
LinkExtractor原语,支持允许/拒绝模式、域过滤器、CSS/XPath范围限定、扩展名过滤和规范化 - 可在模板内使用或单独使用。 - 📦 Built-in Export: 通过钩子和自定义管道导出结果,或使用内置的JSON/JSONL/CSV/XML导出器,如
result.items.to_json()、to_jsonl()、to_csv()和to_xml()。
高级网站抓取(支持会话)
- HTTP Requests: 使用
Fetcher类进行快速且隐蔽的HTTP请求。可模拟浏览器的TLS指纹、头部,并支持HTTP/3。 - Dynamic Loading: 通过
DynamicFetcher类支持Playwright的Chromium和Google Chrome,实现完全浏览器自动化,获取动态网站。 - Anti-bot Bypass: 通过
StealthyFetcher和指纹欺骗实现高级隐身功能。可自动轻松绕过所有类型的Cloudflare Turnstile/Interstitial。 - Session Management: 通过
FetcherSession、StealthySession和DynamicSession类实现持久化会话支持,用于跨请求的cookie和状态管理。 - Proxy Rotation: 内置
ProxyRotator,支持所有会话类型的循环或自定义轮换策略,以及每个请求的代理覆盖。 - Domain & Ad Blocking: 阻止对特定域(及其子域)的请求,或在基于浏览器的抓取器中启用内置广告拦截(约3,500个已知广告/跟踪域)。
- DNS Leak Prevention: 可选的DNS-over-HTTPS支持,通过Cloudflare的DoH路由DNS查询,防止使用代理时DNS泄露。
- Remote Browsers: 无需在本地启动浏览器,通过
cdp_url连接到已在运行的浏览器,无论是同一台机器、另一台主机还是受管浏览器提供商。您还可以使用executable_path将任何浏览器抓取器指向您自己的Chromium构建。 - Background API Capture: 将URL模式传递给
capture_xhr,页面加载时产生的所有匹配XHR/fetch响应都会被收集为Response对象,存储在response.captured_xhr中 - 无需自行逆向工程请求即可获取网站的API数据。 - Async Support: 所有抓取器和专用异步会话类均提供完整的异步支持。
自适应抓取与AI集成
- 🔄 Smart Element Tracking: 使用智能相似度算法在网站变更后重新定位元素。
- 🎯 Smart Flexible Selection: CSS选择器、XPath选择器、基于过滤器的搜索、文本搜索、正则搜索等。
- 🔍 Find Similar Elements: 自动定位与已找到元素类似的元素。
- 🤖 MCP Server to be used with AI: 内置MCP服务器,用于AI辅助的网页抓取和数据提取。MCP服务器具有强大的自定义能力,利用Scrapling提取目标内容,然后传递给AI(Claude/Cursor等),从而加快操作速度并通过最小化token使用降低成本。(演示视频) 它还可以跨调用保持浏览器会话打开、截取页面截图以及通过CDP驱动远程浏览器。
- 🧠 Agent Skill: 一个即装即用的 Agent Skill,用于教导编码代理整个库,使其使用Scrapling编写的代码匹配当前API,而不是猜测。
高性能与经过实战验证的架构
- 🚀 闪电般快速:优化后的性能超越大多数 Python 爬虫库。
- 🔋 内存高效:优化数据结构与懒加载,实现极低内存占用。
- ⚡ 快速 JSON 序列化:比标准库快 10 倍。
- 🏗️ 经过实战验证:Scrapling 不仅拥有 92% 的测试覆盖率和完整的类型提示覆盖率,过去一年已被数百个网络爬虫每日使用。
开发者/网络爬虫友好体验
- 🎯 交互式爬虫 Shell:可选内置 IPython shell,集成 Scrapling、快捷键和新工具以加速爬虫脚本开发,例如将 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')
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: # 保持浏览器打开直至完成
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()
爬虫
构建完整的爬虫,支持并发请求、多种会话类型和暂停/恢复:
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"Scraped {len(result.items)} quotes")
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,它将从停止处继续。
或者直接使用现成的模板来跳过编写爬取逻辑,例如拉取整个 Shopify 商店的商品目录:
from scrapling.spiders import ShopifySpider
class MyStore(ShopifySpider):
target_website = "example.com"
result = MyStore().start() # 商店中的每个商品,每个变体一个条目
高级解析与导航
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 包含一个强大的命令行界面:
启动交互式 Web Scraping 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 Scraping Shell。完整文档请参见这里
性能基准测试
Scrapling 不仅功能强大,而且速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了对比。
文本提取速度测试(5000 个嵌套元素)
| # | 库名称 | 时间 (ms) | 与 Scrapling 对比 |
|---|---|---|---|
| 1 | Scrapling | 1.98 | 1.0x |
| 2 | Parsel/Scrapy | 1.99 | 1.005 |
| 3 | Raw Lxml | 2.48 | 1.253 |
| 4 | PyQuery | 23.15 | ~12x |
| 5 | Selectolax | 196.09 | ~99x |
| 6 | MechanicalSoup | 1531.24 | ~773.4x |
| 7 | BS4 with Lxml | 1535.19 | ~775.3x |
| 8 | BS4 with html5lib | 3388.16 | ~1711.2x |
元素相似性与文本搜索性能
Scrapling 自适应的元素查找能力显著优于其他方案:
| 库名称 | 时间 (ms) | 与 Scrapling 对比 |
|---|---|---|
| Scrapling | 2.29 | 1.0x |
| AutoScraper | 12.46 | 5.441x |
所有基准测试结果为 100 次以上运行的平均值。测试方法见 benchmarks.py。
安装
Scrapling 需要 Python 3.10 或更高版本:
pip install scrapling
[!IMPORTANT] 此安装仅包含解析引擎及其依赖,不含任何 fetcher 或命令行依赖。因此,单独通过此安装导入
scrapling.fetchers或scrapling.spiders(如以上示例所示)会引发ModuleNotFoundError。如果你打算使用任何 fetcher 或 spider,请先安装其依赖,如下所示。
可选依赖
-
如果你打算使用以下任何额外功能、fetcher 或其类,则需要安装 fetcher 依赖及其浏览器依赖,操作如下:
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]" - 安装 shell 功能(Web Scraping shell 和
extract命令):pip install "scrapling[shell]" - 安装全部功能:
pip install "scrapling[all]"
请注意,在安装上述任何额外功能后,仍需运行
scrapling install安装浏览器依赖(如果尚未安装)。 - 安装 MCP 服务器功能:
Docker
你也可以通过以下命令从 DockerHub 安装包含所有额外功能和浏览器的 Docker 镜像:
docker pull pyd4vinci/scrapling
或者从 GitHub 仓库下载:
docker pull ghcr.io/d4vinci/scrapling:latest
该镜像由 GitHub Actions 自动构建并推送,基于仓库的主分支。
贡献
欢迎贡献!在开始之前,请阅读我们的贡献指南。
免责声明
[!CAUTION] 本库仅供教育和研究目的使用。使用本库即表示您同意遵守当地和国际的数据抓取及隐私法规。作者和贡献者不对任何滥用本软件的行为负责。请始终尊重网站的条款和 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 子模块







